0

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!

2
  • What is your lobbyState? It would probably be an array so you would have to append the data to it. Commented May 31, 2021 at 3:32
  • It is ab object with properties defined with an interface Commented May 31, 2021 at 23:35

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.