hello devs I'm trying to save my dark mode in localstorage but I can't I've been trying for hours and I don't see documentation that works for me I'm using svelte not sveltekit Sorry for my english i'm not a native and sorry for my ask i am new in development and in stackoverflow
// This is my store but not work the localStorage
import {writable} from 'svelte/store';
const storedTheme = localStorage.getItem("darkmode");
export let darkmode=writable(storedTheme);
darkmode.subscribe(value => {
localStorage.setItem("darkmode", value===false ? false : true);
});
// and in my switch archieve i got this
<script>
import {darkmode} from '../store/Store';
const handleClick=()=>{
darkmode.update(darkmode=>!darkmode);
};
</script>
localStorage.setItem converts the value to a string before storing it. If you do localStorage.getItem('darkmode') in the JS console then you'll likely get "true" or "false" rather than true or false.
It's hard to know whether this is what's causing your issue without seeing how you are using the value of darkmode in your view. If you're treating it like a Boolean, I would expect it to always be in dark mode, since the strings "true" and "false" both convert to the Boolean value true.
If this is what's happening, the easiest way to fix it would be with something like this:
const storedTheme = localStorage.getItem("darkmode") === "true";
More generally, if you want to store non-string values in localStorage then you may want to consider serializing/deserializing them using JSON.stringify/JSON.parse. This will handle your Boolean case here, as well as more complicated things like an object.