Search code examples
sessionsveltegotosapper

Reloading current page to fill session


I'm having an issue with the session not been filled after login-ing, but if I refresh the page manually it does. So as a workaround I'm trying to reload my login page after login was successful so the session will be populated with the data.

How do is use the goto? i tired goto('/') but it opens the index page. I'm looking for something dynamic and not use the page name.

And does anybody have an idea how to fill the session without reloading the page? session is been filled in 'sapper.middleware' in the server.js coed.


Solution

  • Because session is a store, you can write to it in the browser, as long as you're careful to match what it would be populated with server-side. This is a useful pattern:

    <script>
      import { stores } from '@sapper/app';
    
      const { session } = stores();
    
      async function login() {
        const res = await fetch('auth/login', {
          credentials: 'include',
          method: 'post',
          body: JSON.stringify(whatever)
        });
    
        if (res.ok) {
          session.update(store => ({
            ...store,
            user: await res.json()
          });
        } else {
          // handle the error
        }
      }
    </script>
    
    {#if $session.user}
      <h1>Welcome back {$session.user.name}!</h1>
    {:else}
      <button on:click={login}>log in</button>
    {/if}
    

    If you do need to force a reload, location.reload() does the trick.