Skip to content

Commit

Permalink
fix: lifecycle_outside_component (#304)
Browse files Browse the repository at this point in the history
  • Loading branch information
jianyuan authored Dec 11, 2024
1 parent 24cf932 commit 90b798d
Show file tree
Hide file tree
Showing 5 changed files with 20 additions and 14 deletions.
2 changes: 1 addition & 1 deletion src/app.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ declare namespace App {
// interface Error {}
interface Locals {
pb: import('pocketbase').default
user: import('pocketbase').default['authStore']['model']
user: import('pocketbase').default['authStore']['record']
}
// interface PageData {}
// interface Platform {}
Expand Down
8 changes: 0 additions & 8 deletions src/hooks.client.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const handle: Handle = async ({ event, resolve }) => {
}

event.locals.pb = pb
event.locals.user = pb.authStore.model
event.locals.user = pb.authStore.record

const response = await resolve(event)

Expand Down
6 changes: 3 additions & 3 deletions src/lib/contexts/user.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { AuthModel } from 'pocketbase'
import type { AuthRecord } from 'pocketbase'
import { getContext, setContext } from 'svelte'
import type { Writable } from 'svelte/store'

const userKey = Symbol('user')

export function setUserContext(user: Writable<AuthModel>) {
export function setUserContext(user: Writable<AuthRecord>) {
setContext(userKey, user)
}

export function getUserContext() {
return getContext<Writable<AuthModel>>(userKey)
return getContext<Writable<AuthRecord>>(userKey)
}
16 changes: 15 additions & 1 deletion src/routes/+layout.svelte
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
<script lang="ts">
import '../app.postcss'
import { browser } from '$app/environment'
import { applyAction, enhance } from '$app/forms'
import { setUserContext } from '$lib/contexts/user'
import { pb } from '$lib/pocketbase'
import type { Snippet } from 'svelte'
import { onDestroy, type Snippet } from 'svelte'
import { writable } from 'svelte/store'
import type { PageData } from './$types'
Expand All @@ -15,8 +16,21 @@
let { data, children }: Props = $props()
// Initialize user store
const user = writable(data.user)
setUserContext(user)
if (browser) {
// Load user from cookie (client-side only)
pb.authStore.loadFromCookie(document.cookie)
// Update user store when auth store changes
const unsubscribe = pb.authStore.onChange(() => {
user.set(pb.authStore.record)
document.cookie = pb.authStore.exportToCookie({ httpOnly: false })
}, true)
onDestroy(unsubscribe)
}
</script>

<div class="bg-neutral text-neutral-content">
Expand Down

0 comments on commit 90b798d

Please sign in to comment.