Skip to content

Commit

Permalink
fix: get initial theme synchronously
Browse files Browse the repository at this point in the history
  • Loading branch information
ivopr committed May 27, 2023
1 parent 1016d6f commit 0085537
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 18 deletions.
22 changes: 6 additions & 16 deletions apps/client/src/context/ThemeContext.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
import {
createContext,
ReactNode,
useContext,
useEffect,
useState
} from "react";
import { getCookie, hasCookie, setCookie } from "cookies-next";
import { createContext, ReactNode, useContext, useState } from "react";
import { setCookie } from "cookies-next";

export type Theme = "light" | "dark";

Expand All @@ -16,19 +10,15 @@ interface ContextProps {

interface ProviderProps {
children: ReactNode;
defaultTheme: Theme;
}

const ThemeContext = createContext({} as ContextProps);

export function ThemeProvider({ children }: ProviderProps) {
const [theme, setTheme] = useState<Theme>("light");
const themeCookieKey = "VISUALDYNAMICS_THEME";
export const themeCookieKey = "VISUALDYNAMICS_THEME";

useEffect(() => {
if (hasCookie(themeCookieKey)) {
setTheme(getCookie(themeCookieKey) as Theme);
}
}, []);
export function ThemeProvider({ children, defaultTheme }: ProviderProps) {
const [theme, setTheme] = useState<Theme>(defaultTheme);

function toggleTheme() {
setCookie(themeCookieKey, theme === "light" ? "dark" : "light", {
Expand Down
12 changes: 10 additions & 2 deletions apps/client/src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import React from "react";
import { QueryClientProvider } from "@tanstack/react-query";
import { getCookie, hasCookie } from "cookies-next";
import { type AppProps } from "next/app";
import dynamic from "next/dynamic";
import Head from "next/head";
import { SessionProvider } from "next-auth/react";

import { PageLoadingIndicator } from "@app/components/Loading/PageLoadingIndicator";
import { ThemeProvider } from "@app/context/ThemeContext";
import {
Theme,
themeCookieKey,
ThemeProvider
} from "@app/context/ThemeContext";
import { queryClient } from "@app/lib/query-client";

import "@app/styles/globals.css";
Expand Down Expand Up @@ -42,6 +47,9 @@ export default function App({
pageProps: { session, ...pageProps }
}: AppProps) {
if (typeof window === "undefined") React.useLayoutEffect = React.useEffect;
const defaultTheme = hasCookie(themeCookieKey)
? getCookie(themeCookieKey)
: "light";

return (
<>
Expand All @@ -53,7 +61,7 @@ export default function App({
</Head>
<SessionProvider session={session}>
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<ThemeProvider defaultTheme={defaultTheme as Theme}>
<NextNProgress
height={5}
color="#22c55e"
Expand Down

0 comments on commit 0085537

Please sign in to comment.