Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 777
AriBer Avatar asked Oct 25 '25 14:10

AriBer


1 Answers

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.

like image 129
Rich Harris Avatar answered Oct 27 '25 18:10

Rich Harris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!