Boubou
Boubou

Reputation: 742

State not updated using Redux toolkit with Typescript

Using createAsyncThunk and extraReducers, I can get data, but the state isn't updated. Here's the code

// matchMakingSlice.ts
export const getOpenChallenges = createAsyncThunk(
  "openchallenges/get",
  async () => {
    const response = await fetchWrapper<Lobby>("api/p/openchallenges", "GET");
    return response;
  }
);

export const matchMakingSlice = createSlice({
  name: "matchMaking",
  initialState: lobbyState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getOpenChallenges.fulfilled, (state, action) => {
  state = action.payload;
    });
  },
});

export default matchMakingSlice.reducer;

Here I can see the data in the payload, but when I set the state, it doesn't do what I think it would do... Reduc Chrome Addon shows me an empty state. I get the same result trying to use a selector in a component.

Here more infos:

// store.ts
const store = configureStore({
  reducer: {
    matchMaking: mathMakingReducer,
    user: userReducer,
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();

export default store;

// component.ts
const Lobby = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getOpenChallenges());
  }, [dispatch]);

  const challenges = useSelector((state: RootState) => {
    return state.matchMaking.openChallenges;
  });

What I am doing wrong? Thanks!

Upvotes: 0

Views: 1026

Answers (1)

markerikson
markerikson

Reputation: 67439

state = action.payload is never a valid operation in an Immer-powered reducer. Immer works by tracking mutations to existing state, or letting you return a new value. state = just changes the local state variable to point to something different, which is neither a mutation nor a return. You need return action.payload.

See the RTK "Writing Reducers with Immer" docs page for further details on this.

Upvotes: 2

Related Questions