Skip to content

Commit

Permalink
ref: use Svelte context to pass user to child components to prevent f…
Browse files Browse the repository at this point in the history
…lashing
  • Loading branch information
jianyuan committed Oct 27, 2024
1 parent 4c655d4 commit 323e6a8
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 16 deletions.
4 changes: 2 additions & 2 deletions src/hooks.client.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { pb } from '$lib/pocketbase'
import { currentUser } from '$lib/stores/user'
import { setContext } from 'svelte'

pb.authStore.loadFromCookie(document.cookie)
pb.authStore.onChange(() => {
currentUser.set(pb.authStore.model)
setContext('user', pb.authStore.model)
document.cookie = pb.authStore.exportToCookie({ httpOnly: false })
}, true)
4 changes: 0 additions & 4 deletions src/lib/stores/user.ts

This file was deleted.

13 changes: 5 additions & 8 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
<script lang="ts">
import '../app.postcss'
import type { Snippet } from 'svelte'
import { setContext, type Snippet } from 'svelte'
import { applyAction, enhance } from '$app/forms'
import { pb } from '$lib/pocketbase'
import { currentUser } from '$lib/stores/user'
import type { PageData } from './$types'
interface Props {
Expand All @@ -14,10 +13,8 @@
let { data, children }: Props = $props()
// Set the current user from the data passed in from the server
$effect(() => {
currentUser.set(data.user)
})
// Add the user to the context so we can access it in other components
setContext('user', data.user)
</script>

<div class="bg-neutral text-neutral-content">
Expand All @@ -27,8 +24,8 @@
</div>
<div class="navbar-end">
<ul class="menu menu-horizontal">
{#if $currentUser}
<li><a href="/">{$currentUser.email}</a></li>
{#if data.user}
<li><a href="/">{data.user.email}</a></li>
<li>
<form
method="POST"
Expand Down
20 changes: 18 additions & 2 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
<h1>Welcome to SvelteKit</h1>
<script lang="ts">
import type { AuthModel } from 'pocketbase'
import { getContext } from 'svelte'
const user = getContext<AuthModel | undefined>('user')
</script>

{#if user}
<p>Logged in as {user.email}</p>
{:else}
<p>Not logged in</p>
{/if}

<p>
Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation
Visit
<a href="https://github.com/jianyuan/pocketbase-sveltekit-auth">
our GitHub repository
</a>
to read the documentation.
</p>

0 comments on commit 323e6a8

Please sign in to comment.