Search code examples
reduxredux-thunkredux-toolkit

Is there a better way of chaining async thunks while catching rejections?


Since a thunk created with createAsyncThunk will always return a resolved promise. Is there a better way of handling chained thunks than having to add unwrapResult each time in order to catch a rejection?

const fetchUsers = createAsyncThunk('users/fetch', myService.fetchUsers);
const updateUser = createAsyncThunk('users/update', myService.updateUser);

export const updateAndFetch = values => async dispatch => {
  const result = await dispatch(updateUser(values));
  const unwrapped = unwrapResult(result); // required to see if first update was rejected
  return dispatch(fetchUsers());
}

Solution

  • Not really.

    You could also write it like

    export const updateAndFetch = values => async dispatch => {
      const result = await dispatch(updateUser(values)).then(unwrapResult);
      return dispatch(fetchUsers());
    }
    

    or

    export const updateAndFetch = values => async dispatch => {
      const result = await dispatch(updateUser(values));
      if (updateUser.fulfilled.match(result)) {
        return dispatch(fetchUsers());
      }
    }
    

    but at some point you'll have to do that check.