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.