0

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!

Luu Bieu Nghi
  • 21
  • 1
  • 6
Neil Nguyen
  • 349
  • 2
  • 7
  • 2
    Have you taken a look at Redux Toolkit? Check out [`createAsyncThunk()`](https://redux-toolkit.js.org/api/createAsyncThunk). – Mike Feb 17 '21 at 15:28
  • Thank Mike, I haven't ever known about Redux Toolkit before. I will research now :D – Neil Nguyen Feb 17 '21 at 15:35
  • See also: https://redux.js.org/tutorials/fundamentals/part-8-modern-redux – Mike Feb 17 '21 at 15:38
  • 1
    @DongNguyenVan Page and category are part of a query so you should save that as something like: `{dataType: {'page=1&category=one':{loading, requested, error, stale, refreshing, data}}}` where data is an array of id's and `page=1&category=one' is the query to get the page as string. the items themselves are stored in `{dataType:{data:{1:{loading, requested, error, stale, refreshing, data:{id:1, otherProps}}}}}` I don't think redux toolkit works with server side filtering or sorting or at least they haven't bothered to add an example for that. – HMR Feb 17 '21 at 17:06
  • HMR, I don't understand about page and categories in your state. Do you have any document or source code about that? – Neil Nguyen Feb 18 '21 at 01:48
  • @Mike is right, toolkit is amazing. Checkout https://www.youtube.com/watch?v=9lCmbth63k0&t=57s&ab_channel=JustinKim incase you want to learn toolkit and know more about the advantages it has to offer over redux. – Tom Bombadil Apr 24 '21 at 04:55

0 Answers0