I'm loading/saving a state for light/dark mode in localstorage, and calling it to a Chakra UI switch, where if its on dark mode(aka turned "on") then the switch will already be on, dark mode, etc. If its in light mode (aka turned "off") then the switch will be turned on the left, however, when I turn the switch on, it takes two clicks to turn back to the left (even though its switching themes):
Loading/Saving Data:
const [theme, setTheme] = useState("light");
const toggleTheme = () => {
setTheme((curr) => (curr === "light" ? "dark" : "light"));
};
const saveState = (state) => {
toggleTheme();
var status = '';
if(state === "light") {
status = "dark";
} else {
status = "light";
}
try {
const currState = JSON.stringify(status)
localStorage.setItem('theme', currState)
} catch(err) {
return undefined;
}
}
const loadState = (state) => {
try {
const loadState = localStorage.getItem(state)
if(loadState === null) {
return undefined;
}
return JSON.parse(loadState)
} catch(err) {
return undefined;
}
};
useEffect(() => {
setTheme(loadState('theme'))
}, []);
Conditional render for button:
{theme === 'dark' ? <Switch onChange={() => saveState(theme)} isChecked id="theme-toggle"/> : <Switch onChange={() => saveState(theme)} id="theme-toggle"/>}