sveltejs/sapper

$session prop is undefined even though JSON.stringify shows it has content

Opened this issue · 7 comments

In my nav.svelte component I have:

{#if $session.token}
  ${JSON.stringify($session.token)} - ${JSON.stringify($session.token.username)}
{/if}

In login.svelte:

const { session } = stores();
  let username, password;
  async function onLogin(username, password){
    const response = await fetch(`auth/login`, {
			method:"POST",
			headers:{ 'Content-Type': 'application/json' },
			body: JSON.stringify({"username":username,"password":password})
    })
    if (response.ok) {
      const json = await response.json();
      session.set({ token: json });
      $session.token = json;
      goto("/");
		} else {
			throw new Error(response);
		}
  }

login.js handler:

 req.session.token = user; //parsed.token;
        console.log(`req.session.token: ${JSON.stringify(req.session.token)}`);
        res.writeHead(200, {
          'Content-Type': 'application/json'
        });
        res.end(JSON.stringify({ token: user }));

server.js:

sapper.middleware({
      session: (req, res) => {
        console.log(`% req.session.token: ${JSON.stringify(req.session.token)}`);
        return ({
          token: req.session.token
        })}
      })

The output in nav.svelte is:
${"token":{"_id":"kjbLgeU8k3GPr6jBd8NkCj","username":"matt123","password":"$2b$10$aXMJc64o9W166OL12CG/A.lWyuB9zdPkaNUsze3Lch6Z2khHaTKY.","access":"user"}} - $undefined

Notice that the data is there, but username outputs undefined. I believe I am doing something wrong but it is obscure.

sjroe commented

session.token.undefined in your Nav.svelte is undefined. Try session.token.username.

session.token.undefined in your Nav.svelte is undefined. Try session.token.username.

Sorry, that was a typo. Fixed.

Another piece of info: If I reload the page (after login) the usename field then displays properly:
${"_id":"kjbLgeU8k3GPr6jBd8NkCj","username":"matt123","password":"$2b$10$aXMJc64o9W166OL12CG/A.lWyuB9zdPkaNUsze3Lch6Z2khHaTKY.","access":"user"} - $"matt123"

I use setTimeout(() => location.replace("/"), 1500); to reload the page for me to prevent this issue.

Thanks @mikeoptics .

It's strange, if I use window.location.href, it works ok, but if I use goto() it has this problem.

Can you try await goto("/");?
As mentioned in the Docs of Sapper, goto() returns a Promise that resolves when the navigation is complete.

Link - https://sapper.svelte.dev/docs#goto_href_options

P.S - awaiting goto() worked for me!

Ah, I will give await a try, thanks @Vaibhav-Kulkarni-4 !