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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With