ThinkGeek
ThinkGeek

Reputation: 5157

Passing callback/promise to action creator from component

I have a react component from where I want to set some state in redux and when state is set I want to do some other stuff in the component.

 // Inside Component
 onButtnClick() {
       const currentTime = moment.tz('US/Eastern').valueOf();
       this.props.updateDataInReduxState(currentTime, () => {
                // this should not be called until current time is set.
                this.props.openInputModalToShowTime();
       });
 }

 // Inside actions
 function updateDataInReduxState(currentTime, callback) {
     // how can I call callback after state updates successfully, 
     // to ensure correct time is shown in the modal?
     return {
        type: UPDATE_TIME,
        payload: currentTime
     }
 )

 function openInputModalToShowTime() {
   return {
        type: SHOW_MODAL,
        payload: true
     }
 }

 // Modal Component listens on redux state state.showmodal, if true it opens 
 // and displays time stored in redux state state.currentTime

Upvotes: 2

Views: 935

Answers (2)

Benjamin Hao
Benjamin Hao

Reputation: 358

I'm no expert, but it seems you just wanna show a modal after the redux state is updated. Since dispatching an action is synchronous, you don't need a callback to do the job. I think you can have a local state(not redux state) in your component called showModal which is initialized to false. Then, in the onButtonClick() function, you dispatch an action to update the redux state, and then call setState to set the local state showModal to true. And in your render function of the component, you have something like {this.state.showModal && <ModalComponent />}. The name ModalComponentis just an example, it might be a simple <div>xxxx</div> instead. Make sure you reset the state to false when you close the modal.

Upvotes: 0

codeslayer1
codeslayer1

Reputation: 3686

You should not be dispatching an action inside another action creator(function updateDataInReduxState in your case). Action creators are simply used to dispatch an action, which in turn is listened by a reducer and state is changed accordingly.

You can handle your case like this.

//Inside component, dispatch updateData action without any callback
onButtnClick() {
    const currentTime = moment.tz('US/Eastern').valueOf();
    this.props.updateDataInReduxState(currentTime);
}

//Now listen to your prop updates and once current time prop is set in your state, dispatch your openInputModalToShowTime action
componentWillReceiveProps(nextProps) {
    if(nextProps.hasOwnProperty('currentTime') && nextProps.currentTime != null){
      this.props.openInputModalToShowTime();
    }
}

Upvotes: 2

Related Questions