Amit
Amit

Reputation: 353

React component is not getting updated when state changes into the redux

REDUX

return{...state,importGridData:importGridData)

Here the importGridData assign to state varialbes inside the redux initial state

Component Render

const {importGridData} = this.props
this.setState({importGrdData,importGridData)

I am getting the data here into the react component using the props And I want assign this data into my datagrid component

<DataGrid data={this.state.importGrdData}

I can not give the setState inside the render method so how can I update my datagrid data?

Is there any thing missing here ?

Thanks in Advance.

Upvotes: 1

Views: 1039

Answers (3)

Araz Babayev
Araz Babayev

Reputation: 1770

I am using "componentWillReceiveProps" lifecycle for recieve next props.

componentWillReceiveProps(nextProps){  
    this.setState({   
        importGrdData:    nextProps,  
    });
}

The code is an example.I hope it can be helpful for you.Thanks

Upvotes: 0

Aruna
Aruna

Reputation: 12022

It looks like you want to update the component state from redux state.

In that case, as mentioned by Bhojendra, you can use componentDidUpdate method as below.

componentDidUpdate(prevProps, prevState) {
  const { importGridData } = this.props;

  if(prevProps.importGridData !== importGridData) {
    // update the state
    this.setState({ importGrdData: importGridData })
  }
}

But, instead of copying the redux state to local state then binding the data to DataGrid, I would recommend directly using the redux state to bind the grid in the render method if you don't have any other dependency.

render() {
   const { importGridData } = this.props;
   return <DataGrid data={importGridData} />;
}

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

It should be colon : not comma ,:

this.setState({importGrdData:importGridData})

Ah, I see spelling difference (Grd and Grid):

Also, you may just write: (because you have same name)

this.setState({importGrdData})


You can update the state in componentDidUpdate hook so that after you get the props it will update the state:

componentDidUpdate(prevProps, prevState) {
  if(this.state.importGrdData !== prevState.importGrdData) {
    // update the state
  }
}

To know more about componentDidUpdate, look at the docs.

Only in rare case, you may use getDerivedStateFromProps.

Upvotes: 0

Related Questions