Search code examples
reactjsreduxstore

In Redux, do I have to import store to access data in this case?


This is my container:

this.setObj(obj)
let activeButton = 0;
anotherObj.options.forEach((option, index) => {
  if (option.id === defaultId) {
    activeButton = index;
    this.setButton(index); //setButton is a common function, so I cannot pass obj as argument to it
  }
});

setObj(obj) {
  this.props.setObj(obj);  //calls an action creator
}

setButton() {
  let {obj} = this.props;
}

my action:

setObj = (obj) => ({
    type: 'SET',
    obj
})

my reducer:

switch(action.type) {
  case 'SET':
    return {...state, id: action.obj}
}

and I have mapStateToProps and mapDispatchToProps.

Now I have find one problem. if I call setObj() in my container, and then call setButton() after that, the obj is not updated. According to Dan, because it is asynchronous. https://github.com/reactjs/react-redux/issues/291

so in this case, should I import store to access the latest obj?

import store from './store'

    setButton() {
      const state = store.getState()
      let { obj } = state;
    }

Solution

  • This happens because of the async nature of javacript you should indeed try to call the getId function from the componentWillReceiveProps

    componentWillReceiveProps(nextProps) {
       if(nextProps.id !== this.props.id) 
        this.getId(nextProps)
    }
    getId(props) {
      console.log(props.id)
    }
    

    If you are using redux thunk you can also make use of .then callback on setId like

    setId(id) {
      this.props.setId(id).then(() => {this.getId()});  //calls an action creator
    }