How to create a context that can be used in all pages in Svelte?

Viewed 317

I'm currently learning Svelte and I would like to create an authentication flow for this side project. Usually, in React, I'm used to saving authenticate information with Contexts.

<AuthContext>
   <App />
<AuthContext>

I would like to know if Svelte can perform a similar approach too? All tutorials are component-based context. I would like to call getContext('authContext') throughout my app.

AuthContext.svelte

<script lang='ts'>
      import { writable } from 'svelte/store'
      import { onDestroy, setContext } from 'svelte'
      import {getAuth, type User, onAuthStateChanged} from 'firebase/auth'
    
      const auth = getAuth()
      const userStore = writable<User | null>(null)
      const isLoggedIn = writable<boolean>(false)
      
      const contexts = {
        isLoggedIn,
        userStore,
        logOut,
      }
      
      const unsubscribe =  onAuthStateChanged(auth, (user) => {
        if(user) {
          userStore.set(user)
          isLoggedIn.set(true)
        }
      })

      setContext('authContext', contexts)
 
    function logOut() {
      auth.signOut()
      isLoggedIn.set(false)
    }
    
    
      onDestroy(() => unsubscribe())
    
</script>
    

I've called getContext in __layout.svelte:

<script lang='ts'>
      import {getContext} from 'svelte'

      const {isLoggedIn} = getContext('authContext')
      
</script>

It produces this error:

Cannot destructure property 'isLoggedIn' of '__vite_ssr_import_1__.getContext(...)' as it is undefined.

2 Answers

For a 'context' to be used in all pages you should probably just use a regular store.

Define the store in an external javascript file:

// ./stores.js
import { writable } from 'svelte/store';

export const loggedIn = writable(false);
export const user = writable(null);

And simply import it where necessary:

<!-- Component.svelte -->
<script>
  import { loggedIn } from './stores.js';
</script>

Not sure if this has to be done via a component in SvelteKit? Couldn't the context be built and set like this? REPL
(I use to do it without context like this REPL)

App.svelte
<script>
    import { setContext } from 'svelte'
    import {authContext} from './authContext'
    import Component from './Component.svelte'

    setContext('authContext', authContext)
</script>

<Component />
authContext.js
import { writable } from 'svelte/store'
import {getAuth, onAuthStateChanged} from 'firebase/auth'

const auth = getAuth()

const userStore = writable(null)
const isLoggedIn = writable(false)

onAuthStateChanged(auth, (user) => {
    if(user) {
        userStore.set(user)
        isLoggedIn.set(true)
    }else {
        userStore.set(null)
        isLoggedIn.set(false)
    }
})

async function logOut() {
    await auth.signOut()
//  isLoggedIn.set(false) // (would handle via onAuthStateChanged) 
}

export const authContext = {
    isLoggedIn,
    userStore,
    logOut,
}
Component.svelte
<script>
    import {getContext} from 'svelte'
    const {isLoggedIn, userStore, logOut} = getContext('authContext')
    
    async function handleLogout(){
        try{
            await logOut()
        }catch(error){
            console.error(error)
        }
    }
</script>

<div>
    isLoggedIn: {$isLoggedIn}<br>
    username:
    {#if $isLoggedIn}
        {$userStore.username}
    {/if}
</div>

<button on:click={handleLogout}>
    logOut
</button>

<style>
    button {
        margin-top: 1rem;
    }
</style>
Related