Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[bug]: useTheme (system) does not update based on user preferences #4094

Open
2 tasks done
joaopaulomoraes opened this issue Jun 24, 2024 · 1 comment
Open
2 tasks done
Labels
bug Something isn't working

Comments

@joaopaulomoraes
Copy link

Describe the bug

Once the theme is set to system, when changing the operating system settings it does not reflect the changes correctly, only after refreshing the page. [Vite]

Screen.Recording.2024-06-24.at.13.mp4

Affected component/components

theme-provider

How to reproduce

  • Change the color mode to system
  • Change system color preferences (appearance [dark, light])

Codesandbox/StackBlitz link

https://stackblitz.com/~/github.com/shadcn/vite-template?file=src/main.tsx

Logs

No response

System Info

Platform: Darwin
Arch: x86_64
Version: Darwin Kernel Version 23.5.0: Wed May  1 20:09:52 PDT 2024; root:xnu-10063.121.3~5/RELEASE_X86_64
Node: v20.13.1
PNPM: 9.1.3

Before submitting

  • I've made research efforts and searched the documentation
  • I've searched for existing issues
@joaopaulomoraes joaopaulomoraes added the bug Something isn't working label Jun 24, 2024
@joaopaulomoraes
Copy link
Author

I found a solution by just adding a listener to the media event so that the theme would be updated again.

import * as storage from 'actions/storage';
import {
  createContext,
  useContext,
  useEffect,
  useState
} from 'react';

type Theme = 'dark' | 'light' | 'system';

type ThemeProviderProps = {
  children: React.ReactNode;
  defaultTheme ? : Theme;
  storageKey ? : string;
};

type ThemeProviderState = {
  theme: Theme;
  setTheme: (theme: Theme) => void;
};

const ThemeProviderContext = createContext < ThemeProviderState > ({
  theme: 'system',
  setTheme: () => null
});

export const ThemeProvider = ({
  children,
  storageKey = '@theme',
  defaultTheme = 'system',
  ...props
}: ThemeProviderProps) => {
  const [theme, setTheme] = useState < Theme > (
    () => storage.get < Theme > (storageKey) || defaultTheme
  );

  useEffect(() => {
    const root = document.documentElement;
    const systemTheme = matchMedia('(prefers-color-scheme: dark)');

    const updateTheme = () => {
      root.classList.remove('light', 'dark');

      if (theme === 'system') {
        root.classList.add(systemTheme.matches ? 'dark' : 'light');
        return;
      }

      root.classList.add(theme);
    };

    updateTheme();
    systemTheme.addEventListener('change', updateTheme);

    return () => {
      systemTheme.removeEventListener('change', updateTheme);
    };
  }, [theme]);

  const value = {
    theme,
    setTheme: (newTheme: Theme) => {
      storage.set(storageKey, newTheme);
      setTheme(newTheme);
    }
  };

  return ( <
    ThemeProviderContext.Provider {
      ...props
    }
    value = {
      value
    } > {
      children
    } <
    /ThemeProviderContext.Provider>
  );
};

export const useTheme = () => {
  const context = useContext(ThemeProviderContext);

  if (context === null) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }

  return context;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant