James
James

Reputation: 3815

Dispatch multiple actions using Redux Thunk and the await/async syntax to track loading

I am currently editing some reducers to be able to track the loading state of axios operations. Most of my async syntax is written in async/await fashion and would like to keep it that way to keep my code organized.

I am not sure how to dispatch two action creators one after the other: the first one to fire off the FETCHING_USER action type and keep track of the reduced isFetching state, while the other one to fire off the actual axios GET request. The code currently looks like this to get the API request:

export const fetchUser = () => async dispatch => {
  const res = await axios.get(`${API_URL}/api/current_user`, {
    headers: { authorization: localStorage.getItem("token") }
  });
  dispatch({ type: FETCH_USER, payload: res.data });
};

I am not sure how to dispatch the FETCHING_USER and then fire off the FETCH_USER action.

Upvotes: 0

Views: 4395

Answers (1)

Artem Mirchenko
Artem Mirchenko

Reputation: 2170

First you need to modify your reducer to have isFetching statement and requesting and receiving data cases:

const INITIAL_STATE = { isFetching: false, data: [] };

export default(state = INITIAL_STATE, action) => {
 switch(action.type) {
  case REQUEST_USER: {
   return {...state, isFetching: true};
  }
  case RECEIVE_USER: {
   return {...state, isFetching: false, data: action.payload};
  }
  default: return state;
 }

}

Then modify your action to use try/catch statements:

export const fetchUser = () => async dispatch => {
 dispatch({ type: REQUEST_USER });

 try {

  const res = await axios.get(`${API_URL}/api/current_user`, {
   headers: { authorization: localStorage.getItem("token") }
  });
  
  dispatch({ type: RECEIVE_USER, payload: res.data });

 }
 catch(e){
   //dispatch your error actions types, (notifications, etc...)
 }

};

Then in component you can use condition like: isFetching ? //show loader : //show content (data[])

Upvotes: 3

Related Questions