jeffbski / redux-logic

Redux middleware for organizing all your business logic. Intercept actions and perform async processing.
MIT License
1.81k stars 107 forks source link

How to delay a dispatch #151

Closed bernard-turing closed 5 years ago

bernard-turing commented 5 years ago

How can I use dispatch inside setTimeout?

const addFavoriteDeveloperLogic = createLogic({
  type: ADD_FAVORIT_DEVELOPER,
  latest: true,
  warnTimeout: 0,
  processOptions: {
    dispatchMultiple: true,
  },
  process({ getState, action }, dispatch, done) {
    return axios.post(routeNames.API_CUSTOMER, action.payload.body)
      .then(resp => resp.data)
      .then(data => {
        dispatch({ type: ADD_FAVORIT_DEVELOPER_SUCCESS, payload: {error: false, showAlert: true, alertMessage: "Added developer to favourite list!"} })
        setTimeout(() => {
          dispatch({ type: ADD_FAVORIT_DEVELOPER_SUCCESS, payload: {error: false, showAlert: false, alertMessage: "Added developer to favourite list!"} });
          done();
        })
      })
      .catch(err => dispatch({ type: ADD_FAVORIT_DEVELOPER_FAILED }))
      .then(() => done());
  }
});
cesarp commented 5 years ago

You can use a timeout but in your example you would need to make sure that you don't call done before.

So you can remove then(() => done()) and put a done inside the catch. You are also missing the second parameter of the setTimeout, how much time do you want to wait?

bernard-turing commented 5 years ago

Thank you @cesarp, it is working now.