From 1fb081cd98f29062c966fc2c778221b43b53959b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Mon, 11 Nov 2024 19:08:38 +0100 Subject: [PATCH] fix(composable): use same context for `clear` and `fetch` (#278) Resolves #273 --- src/runtime/app/composables/session.ts | 43 ++++++++++++-------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/src/runtime/app/composables/session.ts b/src/runtime/app/composables/session.ts index 8d221e5b..1f2c960c 100644 --- a/src/runtime/app/composables/session.ts +++ b/src/runtime/app/composables/session.ts @@ -1,16 +1,31 @@ import { useState, computed, useRequestFetch } from '#imports' import type { UserSession, UserSessionComposable } from '#auth-utils' -const useSessionState = () => useState('nuxt-session', () => ({})) -const useAuthReadyState = () => useState('nuxt-auth-ready', () => false) - /** * Composable to get back the user session and utils around it. * @see https://github.com/atinux/nuxt-auth-utils */ export function useUserSession(): UserSessionComposable { - const sessionState = useSessionState() - const authReadyState = useAuthReadyState() + const sessionState = useState('nuxt-session', () => ({})) + const authReadyState = useState('nuxt-auth-ready', () => false) + + const clear = async () => { + await $fetch('/api/_auth/session', { method: 'DELETE' }) + sessionState.value = {} + } + + const fetch = async () => { + sessionState.value = await useRequestFetch()('/api/_auth/session', { + headers: { + Accept: 'text/json', + }, + retry: false, + }).catch(() => ({})) + if (!authReadyState.value) { + authReadyState.value = true + } + } + return { ready: computed(() => authReadyState.value), loggedIn: computed(() => Boolean(sessionState.value.user)), @@ -20,21 +35,3 @@ export function useUserSession(): UserSessionComposable { clear, } } - -async function fetch() { - const authReadyState = useAuthReadyState() - useSessionState().value = await useRequestFetch()('/api/_auth/session', { - headers: { - Accept: 'text/json', - }, - retry: false, - }).catch(() => ({})) - if (!authReadyState.value) { - authReadyState.value = true - } -} - -async function clear() { - await $fetch('/api/_auth/session', { method: 'DELETE' }) - useSessionState().value = {} -}