2

Fairly new to JS, React. Trying to use Material-table with a add row button. Add row would not add the row. One refreshing the rows are reset. I'm pretty sure I'm doing something wrong with setting/ updating the state.

export default function App() {
  return (
    <div className="App">
      <Tabl
        obj={{
          a: "a",
          items: [{ x: 1 }, { x: 2 }, { x: 3 }]
        }}
      />
    </div>
  );
}

class Tabl extends Component {
  constructor(props) {
    super(props);
    this.state = {
      obj: props.obj
    };
    console.log(JSON.stringify(this.state.obj));
  }

  updateState(newData) {
    this.setState({
      obj: [...this.state.obj.items, newData]
    });
  }

  render() {
    const currObj = this.state.obj;
    const column = [
      {
        title: "a",
        field: "x"
      }
    ];

    const tableIcons = {
      Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
      Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
      Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />)
    };

    return (
      <MaterialTable
        data={currObj.items}
        columns={column}
        icons={tableIcons}
        options={{
          search: false,
          paging: false
        }}
        editable={{
          onRowAdd: (newData) =>
            new Promise((resolve, reject) => {
              setTimeout(() => {
                this.updateState(newData);
                resolve();
              }, 1000);
            })
        }}
      />
    );
  }
}
export default Tabl;

Thanks in advance.

1
  • updateState defenitely seems to be updating the state. But I believe the next render is using the old state and not the updated state Commented Nov 13, 2020 at 8:49

1 Answer 1

2

this.updateState method not binding to class.

You can bind in constructor like this,

constructor(props) {
    super(props);
    this.state = {
      obj: props.obj
    };
    console.log(JSON.stringify(this.state.obj));
    this.updateState= this.updateState.bind(this);
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Your state model is { a: '..', items: [...] } and you are trying to change obj : [...this.state.items, newData]. Maybe it could work this -> obj : {...this.state.obj, items: [...this.state.items, newData]}
Thanks for the hint. obj: { ...this.state.obj, items: [...this.state.obj.items, newData] } worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.