Skip to content

Commit 9ccc9c3

Browse files
committed
ref: use user store with context
1 parent e976b56 commit 9ccc9c3

File tree

4 files changed

+26
-12
lines changed

4 files changed

+26
-12
lines changed

src/hooks.client.ts

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

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

src/lib/contexts/user.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import type { AuthModel } from 'pocketbase'
2+
import { getContext, setContext } from 'svelte'
3+
import type { Writable } from 'svelte/store'
4+
5+
const userKey = Symbol('user')
6+
7+
export function setUserContext(user: Writable<AuthModel>) {
8+
setContext(userKey, user)
9+
}
10+
11+
export function getUserContext() {
12+
return getContext<Writable<AuthModel>>(userKey)
13+
}

src/routes/+layout.svelte

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
<script lang="ts">
22
import '../app.postcss'
33
4-
import { setContext, type Snippet } from 'svelte'
4+
import type { Snippet } from 'svelte'
5+
import { writable } from 'svelte/store'
56
import { applyAction, enhance } from '$app/forms'
7+
import { setUserContext } from '$lib/contexts/user'
68
import { pb } from '$lib/pocketbase'
79
import type { PageData } from './$types'
810
@@ -13,8 +15,8 @@
1315
1416
let { data, children }: Props = $props()
1517
16-
// Add the user to the context so we can access it in other components
17-
setContext('user', data.user)
18+
const user = writable(data.user)
19+
setUserContext(user)
1820
</script>
1921

2022
<div class="bg-neutral text-neutral-content">
@@ -24,8 +26,8 @@
2426
</div>
2527
<div class="navbar-end">
2628
<ul class="menu menu-horizontal">
27-
{#if data.user}
28-
<li><a href="/">{data.user.email}</a></li>
29+
{#if $user}
30+
<li><a href="/">{$user.email}</a></li>
2931
<li>
3032
<form
3133
method="POST"

src/routes/+page.svelte

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
<script lang="ts">
2-
import type { AuthModel } from 'pocketbase'
3-
import { getContext } from 'svelte'
2+
import { getUserContext } from '$lib/contexts/user'
43
5-
const user = getContext<AuthModel | undefined>('user')
4+
const user = getUserContext()
65
</script>
76

8-
{#if user}
9-
<p>Logged in as {user.email}</p>
7+
{#if $user}
8+
<p>Logged in as {$user.email}</p>
109
{:else}
1110
<p>Not logged in</p>
1211
{/if}

0 commit comments

Comments
 (0)