Search code examples
reduxaxiosredux-thunk

Post request redux thunk


I have GET requests and normally when those succeeded I save data in store, but for POST requests I need to know if it succeeded or not, in order to execute some code (show a message and redirect), the docu says you can use an isLoading variable, but it just says if the service is working but not if it succeeded, if I try to create a new success variable in the store, it will be turned on forever after the request and I don't need that either. I tried returning a promise from the action creator and handle response directly inside the component but it looks like the same to call axios there instead of using redux.

My action creator looks like this:

export function createProject(userId, projectName) {
  return function (dispatch) {
    dispatch({ type: projectsActions.START_CREATE_PROJECT });
    return ProjectsService.createProject(userId, projectName).then(() => {
      dispatch({ type: projectsActions.SUCCESS_CREATE_PROJECT });
    }).catch((error) => {
      dispatch({ type: projectsActions.ERROR_CREATE_PROJECT });
      throw error;
    });
  }
}

Solution

  • I understand where your doubts are coming from, it doesn't seem appropriate to have a field on your Redux store only to know the success of a one-time request.

    If you only need to make a post request and only care about it's result once, the simplest way to do it is to use state in the component making the request. Component-level state is easily manageable and gets removed from memory when the component is unmounted, but on the other hand you may want to have a single source of truth for your app. You have to make a choice, but your Redux implementation is correct.