@mickyginger
Posted
Hey RyanC, this looks great!
I'm not familiar with Svelte but checking localStorage
, the countries-color-setting
value never changes when you toggle dark mode.
I think the problem might be on this line:
if (darkModeSaved != null) darkModeSaved = darkModeSaved === 'true';
The logic is quite complex because you're attempting to save the string values true
and false
in localStorage
which are both truthy
, and you also have to deal with null
.
I would instead use the 1 and 0, rather than 'true' and 'false'. I would also probably call the localStorage key something like isLightMode
because it's a bit more idiomatic, and the default (or null value) would be dark mode on (or isLightMode: 0
).
This should make your toggle method a little easier to reason about:
function toggleLightMode() {
const isLightMode = +localStorage.getItem('isLightMode');
localStorage.setItem('isLightMode', isLightMode ? 0 : 1);
}
You'll notice the "+" in front of localStorage
that converts the value returned from getItem
into a number, so '1' becomes 1, '0' becomes 0 and null also becomes '0'. This is called a unary operator.
In the setItem
method I'm using a turnary operator, this is basically an inline if / else statement. If isLightMode
is truthy (ie not 0), then set isLightMode
to 1 otherwise set it to 0.
Now you should be able to make your load
method a bit more terse... something like:
export async function load() {
if (!browser) return {};
let isLightMode = +localStorage.getItem('isLightMode');
let prefersDarkTheme = window.matchMedia('(prefers-color-scheme: dark)').matches;
return {
props: {
darkModeEnabled: !isLightMode ?? prefersDarkTheme
}
};
}
Marked as helpful
@Co1eCas3
Posted
@mickyginger That is a good idea, thank you for that!
Actually, there was no issue saving to localStorage at all, in fact nothing was wrong at all w/ the code. Determined there is a bug in Sveltekit where edits to the __layout props are not retained on navigation for some reason. I've found there is already a github issue open regarding it.