ComponentDidMount not getting called after redux state update?

Asool picture Asool · Feb 11, 2018 · Viewed 9.7k times · Source

I think I'm missing a concept here about React and Redux. I'm trying to work with objects stored in redux, and I'm having trouble.

REDUX: I have an action fetchItems, that gets all items from the database. This action works successfully.

REACT: I have a container, UserProfile, that calls fetchItems in componentDidMount.

The problem I'm seeing is that this.props.items is always null (even though fetchItems is successful). The only way I can detect that items were stored in redux store is if I use componentWillRecieveProps(nextProps). Here, I successfully see the items in nextProps. I feel like using componentWillReceiveProps might be too "messy" though. I guess what I'm asking is, what is the standard way of dealing with updates to redux states in react?

Aseel

Answer

Not the best answer picture Not the best answer · Feb 11, 2018

The cycle will be :

  • constructor()
  • componentWillMount() (will be soon deprecated by the way : https://medium.com/@baphemot/whats-new-in-react-16-3-d2c9b7b6193b)
  • render() => first render (this.props.items, coming from mapStateToProps will be undefined)
  • componentDidMount() => launching fetchItems() => changing redux state => changing the this.props.items => launching the second render() where this.props.items will be set.

So :

  • you should have two console.log('[Render]: Items: ', this.props.items);
  • you should deal with a "loading" state when the this.props.items is null

If the second console.log is still null, Try to add log in your reducer, in the mapStateToProps, ... perhaps it's not state.items.items ...