import { createContext, useState } from "react";
export interface TypeContext {
darkMode: true | false;
setDarkMode: React.Dispatch<React.SetStateAction<boolean>>;
toggleMode: () => void;
}
export interface TypeChildrenProps {
children: JSX.Element;
}
export const GlobalThemeContext = createContext<TypeContext>({
darkMode: false,
setDarkMode: () => {},
toggleMode: () => {},
});
export const ThemeContextProvider = ({ children }: TypeChildrenProps) => {
const [darkMode, setDarkMode] = useState(false);
// useState(localStorage.getItem('Mode') ? JSON.parse(localStorage.getItem('Mode') : false))
// Argument of type 'string | null' is not assignable to parameter of type 'string'.
// Type 'null' is not assignable to type 'string'
const toggleMode = () => {
setDarkMode(!darkMode);
};
return (
<GlobalThemeContext.Provider value={{ darkMode, setDarkMode, toggleMode }}>
{children}
</GlobalThemeContext.Provider>
);
};
Hello. I type in dark light mode using context with typescript, everything works fine. I have applied it to other pages, when you click the button, the mode changes. The only problem is that it disappears when you refresh it. How can I make it stay in local storage?
2
Answers
Your answer is nearly right
Here, are the changes you can do get it through
Your code does almost work, yet there is no setting of the item from the
localstorage
:Ask yourself if it is necessary to have the
Mode
as JSON. Maybe a boolean will do just fine – that would take away the possible parsing error.