I am trying to set initial state of redux slice with a enum value, but it throws Uncaught TypeError: undefined has no properties
.
The code is:
export const themeTokenSlice = createSlice({
name: "themeToken",
initialState: darkThemeToken,
reducers: {
toggleThemeToken: (state) => {
switch (state.theme) {
case Themes.dark:
state = darkThemeToken;
break;
case Themes.light:
state = lightThemeToken;
break;
default:
return state;
}
}
}
});
export const darkThemeToken: themeState = {
theme: Themes.dark
};
export interface themeState {
theme: Themes;
}
export enum Themes {
dark = "dark",
light = "light",
}
The way it works:
export const darkThemeToken: themeState = {
theme: "dark" as Themes.dark
};
Is there a way to initialize the state with enum?
2
Answers
This is how your code should look like (i think so)
but you had issues with types, now they should be resolved
The issues I see in the code:
The code attempts to use
darkThemeToken
andThemes
before they are declared. The variables and types should be declared before using them, so movethemeState
, theThemes
enum, anddarkThemeToken
andlightThemeToken
declarations above thethemeTokenSlice
slice declaration where they are referenced.The
toggleThemeToken
reducer is reassigning the state. In Redux-Toolkit you can either mutate the current state or return new state, never both, and never reassign thestate
a different value.Examples:
There is a logical issue/bug where you are returning the "dark theme" value when the current state is already the dark theme, and vice-versa for the light theme. These values should be inverted, i.e. if the current state is the dark theme, then update to the light theme.
Example Refactor:
themeToken.slice.ts
Demo