Search code examples
javascriptreduxredux-thunk

Redux and promise progress


How can I handle and promise progress in redux ?

I want to show some spinning bar or something while the promise is executing, I'm using axios to handle the requests, but they have an api to handle the progress that goes like this in the config object of the request:

{  
   progress: function(progressEvent) {
       // Do whatever you want with the native progress event
   }
}

But I can only send the request in a redux action, like:

return {
    type: "HTTP_REQUEST",
    payload: axios.get("/webAPI/data", configObj)
}

How can I handle the progress event with those conditions?


Solution

  • If you're looking at just showing a spinner as opposed to a progress bar you really don't need the progress function. Rather I would recommend something along these lines:

    const axiosAction = function(configObj) {
      // We have to thunk the dispatch since this is async - need to use the thunk middleware for this type of construct
      return dispatch => {
        /* action to notify the spinner to start (ie, update your store to have a
        loading property set to true that will presentationally start the spinner) */
        dispatch({
          type: 'AXIOS_REQUEST_STARTING'
        });
        return axios.get("/webAPI/data", configObj)
            .then(res => {
              /* action to set loading to false to stop the spinner, and do something with the res */
              return dispatch({
                type: 'AXIOS_REQUEST_FINISHED',
                payload: res,
              })
            })
            .catch(err => /* some error handling*/);
      };
    }
    

    Edited to add link for redux-thunk