Skip to content

Access original response body from pending createAsyncThunk #507

Closed
@will-amaral

Description

@will-amaral

I'm using createAsyncThunk to handle all my api resquests. However, when I'm doing the error handling in the rejected action, I can't seem to access the original body returned from the response.

export const addContact = createAsyncThunk('contacts/addContactStatus', async (obj) => {
  const { data } = await api.post('/contact/', obj);
  return data;
});

const contactsSlice = createSlice({
  name: 'contacts',
  initialState,
  reducers,
   extraReducers: {
    [addContact.pending]: (state) => {
      state.loading = true;
    },
    [addContact.rejected]: (state, action) => {
      state.loading = false;
// I want to use error.response.data.message, which is how I normally 
// handle errors when using Axios directly,
// But I can't seem to access it
      message.error(action.error.message);
    },
    [addContact.fulfilled]: (state, action) => {
      message.success('Contato criado com sucesso');
      state.loading = false;
      state.entities.push(action.payload);
      state.selected.push(action.payload);
    },
}

I really don't want to do the usual try/catch, since it kinda defeats the purpose of having the status action creators, which I think are great for making my code cleaner. I've looked through the past issues, but maybe I'm missing something. It would be great if someone could help me.

Thanks in advance!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions