I'm trying to import typescript in my redux application. I use redux toolkit createSlice function like this:
const slice = createSlice({
name: sliceName,
initialState,
reducers: {
updateMode(state: SliceState, action: PayloadAction<ModePayload>) {
state = action.payload.mode;
},
},
});
When I dispatch a updateMode action, I receive the following error:
Error: A case reducer on a non-draftable value must not return undefined
But my action.payload is well defined and redux toolkit is up to date. It have something to do with my code but I can't figure it out...
I tried to return state in updateMode and it works, but I get a TypeScript error:
Type '(state: SliceState, action: { payload: ModePayload; type: string; }) => SliceState' is not assignable to type 'CaseReducer<"SHOW_LIST", { payload: any; type: string; }> | CaseReducerWithPrepare<"SHOW_LIST", PayloadAction<any, string, any, any>>'.
Type '(state: SliceState, action: { payload: ModePayload; type: string; }) => SliceState' is not assignable to type 'CaseReducer<"SHOW_LIST", { payload: any; type: string; }>'.
Type 'SliceState' is not assignable to type 'void | "SHOW_LIST"'.
Type '"SHOW_SKILL"' is not assignable to type 'void | "SHOW_LIST"'
Can someone explain to me what am I doing wrong ?
Below my full code:
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
type SliceState = "SHOW_LIST" | "SHOW_SKILL";
let initialState: SliceState = "SHOW_LIST";
const sliceName = "mode";
interface ModePayload {
mode: SliceState;
}
//--- Slice reducer ---
const modeSlice = createSlice({
name: sliceName,
initialState,
reducers: {
updateMode(state: SliceState, action: PayloadAction<ModePayload>) {
return (state = action.payload.mode);
},
},
});
export const { updateMode } = modeSlice.actions;
export default modeSlice.reducer;