Search code examples
initializationglobal-variablessveltesveltekitpageload

Setting a component's variable to localStorage / global variable value on the initial render


I'm using Svelte + SvelteKit.

I'd like to set the initial value of a variable in my component based on the user's previously saved value in localStorage. I can get it to load after the initial load using:

let foo = false;

if (browser) {
  foo = localStorage.collapsed === 'true'
}

This seems to run once the page has loaded, which in my case means there's a flash of the initial value.

I also know I can use <svelte:head> to get the initial localStorage value before the page renders:

<svelte:head>
  <script>
    if (localStorage.foo === 'true') {
      window.foo = true;
    }
  </script>
</svelte:head>

But how can I update my component's value based on this global variable / what's obtained in the <head>?

For CSS, I can attach a class to the documentElement or body but that doesn't help me here.

Repl: https://svelte.dev/repl/3e4099fc70814541ae837ff7da50926a?version=4.2.7


Solution

  • Unless you forego server side rendering and defer the rendering until you are on the client it is not possible (there is no way for the server to know what a user has in localStorage).

    You can wrap your entire component in {#if browser}, turn off SSR, and some other techniques.

    Alternatively, store the data in a cookie, these are sent for every request and therefore available on the server.