The behavior you're seeing—where setting useSession().currentPortfolioId.value = portfolio.id does not immediately reflect the new value when you call useSession().currentPortfolioId.value again—is likely due to how your composable is structured. Each call to useSession() creates a new instance and, therefore, a new useCookie ref. This means you're not referencing the same reactive ref across calls.
How to fix:
You should ensure that your composable returns a singleton ref, not a new one each time. In Nuxt, you can use the useState composable to persist a value across the app, or you can define your composable so it only creates the ref once.
Example fix:
let currentPortfolioId: Ref<number | undefined>;
export function useSession() {
if (!currentPortfolioId) {
currentPortfolioId = useCookie<number | undefined>('currentPortfolio', {
maxAge: 60 * 60 * 24 * 14
});
}
return {
currentPortfolioId
}
}
Or, use Nuxt's useState to ensure a singleton:
export function useSession() {
const currentPortfolioId = useCookie<number | undefined>('currentPortfolio', {
maxAge: 60 * 60 * 24 * 14
});
return {
currentPortfolioId
}
}
But always call useSession() once and reuse the returned object, rather than calling it multiple times in the same scope.
Key point:
If you call useSession() multiple times, you get different refs, so updating one does not update the other. Store the result of useSession() in a variable and reuse it.
References:
This pattern is consistent with how reactivity and composables work in Nuxt and Vue, as shown in the Nuxt useCookie documentation.