How do i Handle state in next js across all pages whether 'use server' or 'use client'?, what I'm trying to achieve is after signin the user info is put into a state like 'currentUser',
I've used jotai earlier I removed it for now. so for example I've set it on a successful signin ex: I now have a const[currentUser] = useAtom(user),
how would i use or access the accessToken given from currentUser? since I cant use useAtom in a server component, how do i achieve this?
currently what im doing is just getting the jwt token from the cookie, but im planning to only put the refresh token in my cookie and the accesstoken would only be available in the response after signin.
Hope you guys understand my explanation, I'm a bit lost too.
My Sign in method in a 'use client' component
const handleSignIn = async (values: z.infer<typeof formSchema>) => {
setIsLoading(true);
try {
const res = await fetch(SIGNIN_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify(values),
});
const data = await res.json();
if (data.isError === true) {
setSignInError("Invalid username or password.");
} else {
router.push("/home");
form.reset();
setSignInError("");
toast.success("Success! What's up", {
position: "bottom-right",
});
}
setIsLoading(false);
} catch (error) {
toast.error(
"Uh oh! Something went wrong. There was a problem with your request.",
{
position: "bottom-right",
}
);
setIsLoading(false);
}
};
Here is my ssr Home page, this is where I would like to access the currentUser state and just use currentUser.accessToken in headers.
async function getUserProfile() {
const nextCookie = cookies();
const jwtCookie = nextCookie.get("jwt");
const res = await fetch(USER_PROFILE_URL, {
headers: {
Cookie: `jwt=${jwtCookie?.value}`,
},
cache: "no-store",
});
const data = await res.json();
const userData: User = {
...data.data,
};
if (res.ok) {
return userData;
} else {
throw new Error("Auth is required to access this page.");
}
}
async function HomePage() {
const data: User = await getUserProfile();
return (
<div className="w-full min-h-screen flex flex-col">
<div className="w-full fixed">
<NavigationBar userDetails={data} />
</div>
<div className="w-full mt-16 p-4"></div>
</div>
);
}