1

I'm working on a React game using Zustand and TypeScript. I'm using Zustand to persist the theme (i.e. dark and light modes) and it works fine but react does not register my changes automatically and need to refresh the page to see it.

useThemeStore.ts

import { persist } from "zustand/middleware";
type ThemeType = "light" | "dark";
interface ThemeState {
  theme: ThemeType;
  toggleTheme: () => void;
}
const useThemeStore = create<ThemeState>()(
  persist(
    (set) => ({
      theme: "light",
      toggleTheme: () =>
        set((state) => ({
          theme:
            state.theme === "light"
              ? (state.theme = "dark")
              : (state.theme = "light"),
        })),
    }),
    {
      name: "theme",
    }
  )
);

export default useThemeStore;

button that triggers the change in App.tsx:

<Button onClick={toggleTheme}>Click me!</Button>

monstajoe
  • 25
  • 5
  • You have the wrong syntax - it seems you are mixing up the `immer` syntax with the regular one. You simply need to return the value. So in your ternary operator, you need to do `state.theme === "light" ? "dark": "light"` - no assignments. – Siddhartha Gandhi Mar 09 '23 at 03:47

0 Answers0