I'm working on my project @reduxjs/toolkit
and created UserSlice
like below.
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { User } from "../../models";
export type UserState = User | null;
export const initialUserState: UserState = null;
const UserSlice = createSlice({
name: "User",
initialState: initialUserState,
reducers: {
receiveUser: (state: UserState, action: PayloadAction<UserState>) => {
state = action.payload;
},
clearUser: (state: UserState, _action: PayloadAction<void>) => {
state = null;
},
signIn: (
_,
_action: PayloadAction<{
email: string;
password: string;
}>
) => {},
signInWithToken: (_, _action: PayloadAction<void>) => {},
},
});
export default UserSlice;
signIn
signInWithToken
are action creators just for taking actions in UserSaga
module, so they do nothing.
When I dispatch signIn
action, below error occurs.
index.js:1 Error: A case reducer on a non-draftable value must not return undefined
at createReducer.ts:163
at Array.reduce (<anonymous>)
at createReducer.ts:143
...
This code snippets pattern works fine my other projects, but this project. I can't figure out the reason of this error, so I'm asking this question. Are there any faults in my code?
I believe you're not returning the state in all of your reducers, because when using arrow functions objects need additional round brackets:
reducers: {
receiveUser: (state: UserState, action: PayloadAction<UserState>) => ({
state: action.payload;
}),
clearUser: (state: UserState, _action: PayloadAction<void>) => ({
state : null;
}),
signIn: (
_,
_action: PayloadAction<{
email: string;
password: string;
}>
) => ({}),
signInWithToken: (_, _action: PayloadAction<void>) => ({}),
},