简体   繁体   中英

Call an Async action after updating the react state

I am new to the react js . I have an action ,

export const updateActivePage = (activePage) => {
  return {
    type: UPDATE_ACTIVEPAGE,
    payload: activePage
  }
}

In my reducer ,

const initialState = {
 activePage: 1,
}
case UPDATE_ACTIVEPAGE:  {
      return {
        ...state,
        activePage: activePage
      }
    }

In my container,

handlePageChange = (pageNumber) => {
    this.props.updateActivePage(pageNumber);
    this.props.fetchUserJd(this.props.activePage);
  }

Now Here I want to call this this.props.fetchUserJd(this.props.activePage); function only when the previous action is successfully updated that value. As this is not returning any promise.

Now, I have a solution that is a callback function. But somehow .then is not avaliable in this as the first function is not returning any promise. any help will be helpful .

You can do the folloowing: in your mapDispatchToProps fn return actions like this:

function mapDispatchToProps(dispatch) {
    return {
         updateActivePage: (pageNumber) => {
            return new Promise((resolve, reject) => {
                dispatch(actions.updateVisualState(pageNumber, resolve, reject));
            });
        }
};

in this case, you will be able to use then for your actions in the view:

this.props.updateActivePage(pageNumber).then(()=>{
  this.props.fetchUserJd(this.props.activePage);
})

You just need to choose the right place to resolve the promise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM