Paul
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.ai20 replies