Blog>
Snippets

Error Handling in Async Thunk Actions

Explain how to handle errors within thunk actions effectively, particularly in the context of asynchronous operations involving API calls.
const fetchUserData = (userId) => {
  return async (dispatch, getState) => {
    dispatch({ type: 'FETCH_USER_REQUEST' });
    try {
      const response = await fetch(`https://api.example.com/users/${userId}`);
      if (!response.ok) {
        throw new Error('Error fetching user data');
      }
      const data = await response.json();
      dispatch({ type: 'FETCH_USER_SUCCESS', payload: data });
    } catch (error) {
      dispatch({ type: 'FETCH_USER_FAILURE', error: error.message });
    }
  };
};
This function (`fetchUserData`) is an async thunk action that takes a `userId` as an argument. When called, it first dispatches an action to signify the start of user data fetching. It uses async/await syntax to make an API call. If the API response is not okay, it throws an error. If it is successful, it dispatches a success action with the data. If an error occurs, it dispatches a failure action with the error message.