N
Nuxt5mo ago
Tom

useState working in SSR but undefined in browser

Hey everyone, I'm unsure how to tackle this, I have a composable:
const useUserState = () => useState('user');

export const useUser = () => {
const jwt = useCookie('jwt');
const user = useUserState();

const login = async (body: any) => {
const data = await usePayloadFetch('users/login', { method: 'POST', body });
jwt.value = data.token;
navigateTo('/');
};

const logout = async () => {
jwt.value = undefined;
user.value = undefined;
};

const getUser = async () => {
if (user.value) return user;

const data = await usePayloadFetch('users/me');
user.value = data;

return user;
};

return { token: jwt, getUser, login, logout };
};
const useUserState = () => useState('user');

export const useUser = () => {
const jwt = useCookie('jwt');
const user = useUserState();

const login = async (body: any) => {
const data = await usePayloadFetch('users/login', { method: 'POST', body });
jwt.value = data.token;
navigateTo('/');
};

const logout = async () => {
jwt.value = undefined;
user.value = undefined;
};

const getUser = async () => {
if (user.value) return user;

const data = await usePayloadFetch('users/me');
user.value = data;

return user;
};

return { token: jwt, getUser, login, logout };
};
In the front end if I getUser in the front end and console.log(user.value) it's undefined, but if I return user.value inside getUser() everyone works as expected. I'm misunderstanding how state is used here. Can anyone explain where I'm going wrong?
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server