typescriptsveltesveltekit

How do I use $state inside hooks.client.ts?


I'm trying to implement authentication with Pocketbase and Svelte 5, following this repo.

In $lib/stores/user.svelte.ts I'm creating a $state store (not sure how to call it?):

// src/lib/stores/user.svelte.ts
import { type AuthModel } from 'pocketbase'
export let currentUser: AuthModel | null = $state(null)

In the hooks.client.ts I'm supposed to watch for changes in Pocketbase's auth store, but since $state doesn't work in .ts files I figured I should move that code in +layout.svelte:

// src/+layout.svelte
<script lang="ts">
    import { pb } from '$lib/pocketbase'
    import { currentUser } from '$lib/stores/user.svelte'

    let { children } = $props()

    pb.authStore.loadFromCookie(document.cookie)
    pb.authStore.onChange(() => {
        currentUser = pb.authStore.model
        document.cookie = pb.authStore.exportToCookie({ httpOnly: false })
    }, true)
</script>

{@render children()}

If I understand correctly, $state works only in .svelte and .svelte.ts files and it should make currentUser behave like a normal variable. According to the docs, reassignment should work too. However, in VSCode I'm getting:

Cannot assign to import svelte(constant_assignment)


Solution

  • Assignments only work on local variables or properties not imports/exports.

    You will have to box the value (this is also necessary for primitives, as those are copied rather than referenced), e.g.

    export const currentUser: { value: AuthModel | null } =
        $state({ value: null });
    
    currentUser.value = pb.authStore.model
    

    Playground