Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different actions based on response status code in Redux-Toolkit

I'm trying out Redux-Toolkit and I'm really liking how concise it is but I can't figure out how I'm supposed to read server response status code and dispatch different actions based on that. For instance, I'm sending a sign up request to an API

export const registerRequest = createAsyncThunk(
  'register/registerRequest',
  async (userInfo: RegisterInfo) => {
    const { firstname, lastname, email, password } = userInfo

    const { data } = await axios.post('url/users/create', {
      firstname,
      lastname,
      email,
      password,
    })
    return data
  }
)

I may receive different types of errors but all of them are handled by a single case in my slice

builder.addCase(registerRequest.rejected, (state, action) => {
      state.loading = false
      state.error = action.error
    })

What is the right way to check for a status code and dispatch corresponding action with Redux-Toolkit ?

like image 610
Oleksandr Fomin Avatar asked Aug 30 '25 16:08

Oleksandr Fomin


1 Answers

In this case, you'd want to handle the error in the actionCreator of createAsyncThunk. Being that you're using TS, you'll want to use rejectWithValue so that you can actually get types for the error interface. There are a few examples in the Usage with TypeScript docs here: https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk. If you have multiple known error response formats, I'd recommend adding type guards for those and introduce a utility helper for your reducer(s) because you'll always check those in the rejected case (registerRequest.rejected in this example) when using createAsyncThunk.

like image 84
Matt Sutkowski Avatar answered Sep 02 '25 07:09

Matt Sutkowski