Paul
Paul
NNuxt
Created by Paul on 11/1/2024 in #❓・help
useCookie not being reactive
Anyway, any step to implement retry onResponseError with $fetch? @kapa.ai `$fetch.create({ onResponseError: async () => { await refreshToken() //retry the request } })
20 replies
NNuxt
Created by Paul on 11/1/2024 in #❓・help
useCookie not being reactive
Hmm. The 2nd approach works though. Still kinda weird for me how the cookie inside the custom plugin doesn't update accordingly. @kapa.ai
Perhaps someone in the community could help (?)
20 replies
NNuxt
Created by Paul on 11/1/2024 in #❓・help
useCookie not being reactive
I used the refreshCookie inside the useAuth composable, and now I added fetchUser inside the composable: import { refreshCookie } from '#app' const useAuth = () => { const accessToken = useCookie('at'); const login = async (param) => { const data = await $fetch('/auth/login', { method: 'post', body: param }) accessToken.value = data.access_token refreshCookie('at') await fetchUser() }; async function fetchUser() { try { const response = await $api('/auth/user', {}); user.value = response.data; } catch (error) { console.error('Failed to fetch user data:', error); logout(); } } return { login }; }; And I implemented a custom wrapper for $fetch as a plugin: export default defineNuxtPlugin((nuxtApp) => { const config = useRuntimeConfig() const baseUrl = import.meta.server ? config.apiBaseUrl : config.public.apiBaseUrl const accessTokenCookie = useCookie('at') const api = $fetch.create({ baseURL: baseUrl, headers: { Accept: 'application/json' }, onRequest({ options }) { if (accessTokenCookie.value && !options.headers?.Authorization) { options.headers = { ...options.headers, Authorization: Bearer ${accessTokenCookie.value}, } } }, }) return { provide: { api } } }) However, fetchUser() fails as accessTokenCookie.value is still undefined after the refreshCookie(). How do I fix it? @kapa.ai
20 replies