0
votes

Hello I'm having trouble with a custom hook

right when rendering the component everything is normal creates the key in storage, but when I try to click on the switch theme, my setTheme always goes as light and never as dark

i don't know where i am wrong ..:

code:

export default function App() {
  const [theme, setTheme] = usePersistedState('theme', { type: 'light' });
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? { type: 'dark' } : { type: 'light' });
  };
  console.log(theme.type, 'aa');
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <button
          css={css`
            background: red;
            width: 100px;
            height: 50px;
            border-radius: 10px;
          `}
          onClick={toggleTheme}
        >
          a
        </button>
      </div>
    </ThemeProvider>
  );
}

custom hook:

function usePersistedState(key, type) {
  console.log(key, type, 'xf');
  const [state, setState] = useState(() => {
    console.log('first');
    const storageValue = JSON.parse(localStorage.getItem(key));
    switch (storageValue) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
  });

  useEffect(() => {
    const storageValue = JSON.parse(localStorage.getItem(key));
    if (storageValue !== state.type) {
      localStorage.setItem(key, JSON.stringify(state.type));
    }
  }, [key, state]);
  return [state, setState];
}

example:

https://codesandbox.io/s/vigorous-goodall-x7x7d

gif:

tjs

1

1 Answers

0
votes

in App.js

setTheme(theme.type === "light" ? darkTheme : lightTheme);

will solve your problem !!