Skip to content

Commit 323e6a8

Browse files
committed
ref: use Svelte context to pass user to child components to prevent flashing
1 parent 4c655d4 commit 323e6a8

File tree

4 files changed

+25
-16
lines changed

4 files changed

+25
-16
lines changed

src/hooks.client.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { pb } from '$lib/pocketbase'
2-
import { currentUser } from '$lib/stores/user'
2+
import { setContext } from 'svelte'
33

44
pb.authStore.loadFromCookie(document.cookie)
55
pb.authStore.onChange(() => {
6-
currentUser.set(pb.authStore.model)
6+
setContext('user', pb.authStore.model)
77
document.cookie = pb.authStore.exportToCookie({ httpOnly: false })
88
}, true)

src/lib/stores/user.ts

Lines changed: 0 additions & 4 deletions
This file was deleted.

src/routes/+layout.svelte

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
<script lang="ts">
22
import '../app.postcss'
33
4-
import type { Snippet } from 'svelte'
4+
import { setContext, type Snippet } from 'svelte'
55
import { applyAction, enhance } from '$app/forms'
66
import { pb } from '$lib/pocketbase'
7-
import { currentUser } from '$lib/stores/user'
87
import type { PageData } from './$types'
98
109
interface Props {
@@ -14,10 +13,8 @@
1413
1514
let { data, children }: Props = $props()
1615
17-
// Set the current user from the data passed in from the server
18-
$effect(() => {
19-
currentUser.set(data.user)
20-
})
16+
// Add the user to the context so we can access it in other components
17+
setContext('user', data.user)
2118
</script>
2219

2320
<div class="bg-neutral text-neutral-content">
@@ -27,8 +24,8 @@
2724
</div>
2825
<div class="navbar-end">
2926
<ul class="menu menu-horizontal">
30-
{#if $currentUser}
31-
<li><a href="/">{$currentUser.email}</a></li>
27+
{#if data.user}
28+
<li><a href="/">{data.user.email}</a></li>
3229
<li>
3330
<form
3431
method="POST"

src/routes/+page.svelte

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,20 @@
1-
<h1>Welcome to SvelteKit</h1>
1+
<script lang="ts">
2+
import type { AuthModel } from 'pocketbase'
3+
import { getContext } from 'svelte'
4+
5+
const user = getContext<AuthModel | undefined>('user')
6+
</script>
7+
8+
{#if user}
9+
<p>Logged in as {user.email}</p>
10+
{:else}
11+
<p>Not logged in</p>
12+
{/if}
13+
214
<p>
3-
Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation
15+
Visit
16+
<a href="https://github.com/jianyuan/pocketbase-sveltekit-auth">
17+
our GitHub repository
18+
</a>
19+
to read the documentation.
420
</p>

0 commit comments

Comments
 (0)