Design comparison
Solution retrospective
There's a bug still where the theme is reverting to the initial state on navigation. If anyone can point out what is causing that, would be grateful. Currently makes absolutely no sense to me...
Community feedback
- @mickygingerPosted over 2 years ago
Hey RyanC, this looks great!
I'm not familiar with Svelte but checking
localStorage
, thecountries-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
andfalse
inlocalStorage
which are bothtruthy
, and you also have to deal withnull
.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 (orisLightMode: 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 fromgetItem
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. IfisLightMode
is truthy (ie not 0), then setisLightMode
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 helpful2@Co1eCas3Posted over 2 years ago@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.
0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord