React Context unexpected behavior with App dir layout
Unanswered
Brown bear posted this in #help-forum
Brown bearOP
Is it still possible to use react context in layouts? I'm getting an issue with the dataprovider unmounting and remounting - which causes the data to be reassigned to null. I put 'use client' in all the files.
10 Replies
@Brown bear you can set the expiry on cookies.
Brown bearOP
how would fetching on server side work then? Is it possible you can give an example on how token could be used like that
I highly recommend reading up on basic HTTP before continuing any further with Auth. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
Brown bearOP
well I already use authorization headers when passing tokens. I'm asking how I can retrieve the token from firebase since the only way I have found was by using this method here:
With server side fetching its not very clear on how it would work
const auth = getAuth(firebaseApp);
useEffect(() => {
return onAuthStateChanged(auth, async (user) => {
if (user) {
// User is signed in
const token = await getIdToken(user);
setToken(token);
setUser(user);
setIsLoading(prevState => ({ ...prevState, auth: false })); // Set auth loading to false
} else {
// User is signed out
router.push('/logout');
}
});
}, [auth, router]);With server side fetching its not very clear on how it would work
Since useEffects only work on client side
I guess store user with cookies?? But even then its not clear
Brown bearOP
This is so wierd... The context works properly with pages directory, but not app directory? This is crazy even with 'use client' everywhere
@Marchy https://www.freecodecamp.org/news/create-full-stack-app-with-nextjs13-and-firebase/
Brown bearOP
for some reason even after following this, the context is still behaving strangely. Switching to server side rendering, how can I make it so that I can actually get the user's auth state?
because I need the token in order to know which data to get for a certain user, and since context is in client side, its impossible to get the auth state like that
export default async function DashboardLayout({
children
}: {
children: React.ReactNode
}) {
//context will not work as context is client side
const { user } = useAuth();
if (user === null) {
return <div>loading...</div>
}
const token = await user.getIdToken();
const data = await fetch('/api/get-admin-organization', {
headers: {
'Authorization': `Bearer ${token}`
}
});
console.log(data);because I need the token in order to know which data to get for a certain user, and since context is in client side, its impossible to get the auth state like that
How do you do it? @Marchy