What is the best practice for using Redux to handle full async services?

171 Views Asked by At

I wonder what is the best way to handle an async service using Redux with error, loading, ... and how to implement that? I am currently using Promise an axios to handle API and call 3 actions request, success and failure:

export function requestExample(page = 1, category = "") 
    return dispatch => {
        dispatch(get_Request()); //set isLoading = true
        request.get(`/posts/myPosts`).then(
            response => {
                dispatch(get_Success(response.data)); //set isLoading = false, data = payload.data
            }
        ).catch(error=>{dispatch(get_Failure())}) //set isLoading = false, data = []
    }
}

My response shape object:

{data: [], isLoading: false}

some time I use:

{data: [], isLoading: false, isLoadDone: false}

I handle error by using axios intercepter when create instance of axios, and stack all my error and show them as modal when they happened.

request.interceptors.request.use(
  function (config) {
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.status !== 200)
      store.dispatch(openModal("alert", { title: "Lỗi", text: `Error code: ${error.status} <br> Error content: ${error.statusText} `, type: "Fail" }));
    return Promise.reject(error);
  }
);

I want some comments about my structure and know more about another way to handle async service with better performance and memory. Thanks!

0

There are 0 best solutions below