Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redux-toolkit extraReducers not being invoked

I'm trying out the createAsyncThunk but can't get the extraReducers to fire. Here is what I have right now:

export const getAllAgents = createAsyncThunk(
  "getAllAgents",
  async (token: string) => {
    let headers = new Headers();
    headers.append("Authorization", `Bearer ${token}`);
    headers.append("Content-Type", "application/json");
    const response = await fetch(`${API.endpoint}/data/agent`, {
      method: "get",
      headers,
      redirect: "follow",
    });
    const data = await response.json();
    console.log("Response in thunk: ", { data });
    return data;
  }
);

export const agentSlice = createSlice({
  name: "agentSlice",
  initialState,
  reducers: {},
  extraReducers:
    //builder call back required for typesafety
    //https://redux-toolkit.js.org/usage/usage-with-typescript#type-safety-with-extrareducers
    (builder) => {
      console.log(createNewAgent.fulfilled);
      builder.addCase(createNewAgent.fulfilled, (state, action) => {
        console.log("fulfilled action", { action });
      });
      console.log(getAllAgents.fulfilled);
      builder.addCase(getAllAgents.fulfilled, (state, action) => {
        state.agents = action.payload.agents;
      });
    },
});

I also see the fulfilled action being called in the dev tools: enter image description here

What is amiss?

like image 215
ankitm Avatar asked Oct 20 '25 05:10

ankitm


1 Answers

I had the same problem. My mistake was that I was adding reducers outside of extraReducers.

This was wrong:

const authSlice = createSlice({
  name: 'auth',
  initialState,
  extraReducers: {
    [login.fulfilled]: (state, action) => {},
   },
   [signUp.fulfilled]: state => {}
}
like image 97
Hojat Modaresi Avatar answered Oct 21 '25 21:10

Hojat Modaresi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!