react component state does not reset on subsequent call for same component

199 Views Asked by At

So my Component looks something like this as mentioned below. When the component is rendered for the first time, it sets the state. But for the 2nd call, the props hold new data but it never sets the state.Instead, the state has previous data.Not sure what is making the behaviour.The state I am interested in is 'data'

class MuiTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      order: 'asc',
      orderBy: this.props.columnData[0].id,
      selected: this.props.defaultAllSelect !== undefined && this.props.defaultAllSelect ? this.props.data.map(d=> d[this.props.uniqueKey]) : [],
      data: this.props.isSortable ? this.props.data.sort((a, b) => (a[this.props.columnData[0].id] < b[this.props.columnData[0].id] ? -1 : 1)) : this.props.data,
      page: 0,
      rowsPerPage: this.props.rowsPerPage,
      uniqueKey: this.props.uniqueKey
    };
  }
}
2

There are 2 best solutions below

1
Kevin On

Please try to implement componentWillReceivedProps(nextProps) method and use this.setState(); to update your state.

This may help you: React lifecycle

1
h1b9b On

It's normal as this is the constructor method.
You should read the Component lifecycle methods, doc

For the update part of the lifecycle, it goes:

  1. componentWillReceiveProps()
  2. shouldComponentUpdate()
  3. componentWillUpdate()
  4. render()
  5. componentDidUpdate()