ffxsam
ffxsam

Reputation: 27713

How to make a React component setState() based on a Redux state change?

I think I know the answer to this, but just to make sure:

I want a React component to call this.setState() when the Redux state changes to a certain condition (say, state.dataLoaded === true). Should I somehow use subscribe, or is that too low level and I should instead use connect to map state to props? In which case, I assume something like this would be acceptable:

componentWillReceiveProps(nextProps) {
  if (nextProps.dataLoaded) {
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(nextProps.posts)
    });
  }
}

Upvotes: 8

Views: 8601

Answers (1)

Florent
Florent

Reputation: 12420

You definitively should use connect to do this. When redux's state will change, new props will be generated and will trigger componentWillReceiveProps.

class MyComp extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (nextProps.dataLoaded) {
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(nextProps.posts)
      })
    }
  }
}

export default connect(
  state => ({
    dataLoaded: state.someStore.loaded
  })
)(MyComp)

Upvotes: 14

Related Questions