Search code examples
reduxreact-reduxredux-toolkit

Handling errors with redux-toolkit


The information about the error in my case sits deeply in the response, and I'm trying to move my project to redux-toolkit. This is how it used to be:

catch(e) {
  let warning
  switch (e.response.data.error.message) { 
    ...
  }
}

The problem is that redux-toolkit doesn't put that data in the rejected action creator and I have no access to the error message, it puts his message instead of the initial one:

enter image description here

While the original response looks like this:

enter image description here

So how can I retrieve that data?


Solution

  • Per the docs, RTK's createAsyncThunk has default handling for errors - it dispatches a serialized version of the Error instance as action.error.

    If you need to customize what goes into the rejected action, it's up to you to catch the initial error yourself, and use rejectWithValue() to decide what goes into the action:

    const updateUser = createAsyncThunk(
      'users/update',
      async (userData, { rejectWithValue }) => {
        const { id, ...fields } = userData
        try {
          const response = await userAPI.updateById(id, fields)
          return response.data.user
        } catch (err) {
          if (!err.response) {
            throw err
          }
    
          return rejectWithValue(err.response.data)
        }
      }
    )