ContextAPI get reinitialized in App router
Unanswered
Black-chinned Sparrow posted this in #help-forum
Black-chinned SparrowOP
I'm using App router with "use client" and I want to manage the global state. So I setup my useContext and useReducer from react. And I wrapped my {childeren} element in RootLayout with <AppContext.Provider>.
The problem I face here is, whenever I change the route, my AppContext gets reinitialized with initial data and its not getting the changes I made through useReducer.
Is it ok to use ContextAPI in Nextjs App router with "use client" ? or is there better way to manage global state of the application
The problem I face here is, whenever I change the route, my AppContext gets reinitialized with initial data and its not getting the changes I made through useReducer.
Is it ok to use ContextAPI in Nextjs App router with "use client" ? or is there better way to manage global state of the application
24 Replies
@Cynipid gall wasp for global state. better go with redux
Black-chinned SparrowOP
do you know the reason why the state in my context gets reinitialized if I provide it from RootLayout
@Black-chinned Sparrow do you know the reason why the state in my context gets reinitialized if I provide it from RootLayout
Cynipid gall wasp
its default behavoir of context.
u can read here https://react.dev/reference/react/useContext
u can read here https://react.dev/reference/react/useContext
with redux would it persist on reload?
im managing auth with a global context and when I relaod user gets signed out
Cynipid gall wasp
u can use localStorage, cookies, redux-persist, ..
@Cynipid gall wasp its default behavoir of context.
u can read here https://react.dev/reference/react/useContext
Black-chinned SparrowOP
thanks. but to use useContext we need to define it at the top level component. In App routers, RootLayout is the top level right ? and I have my navigation in the RootLayout which are not getting rerendered when I change the path from /home to /settings like this. But still I am confused why <AppContext.Provider get rerendered.
@Black-chinned Sparrow thanks. but to use useContext we need to define it at the top level component. In App routers, RootLayout is the top level right ? and I have my navigation in the RootLayout which are not getting rerendered when I change the path from /home to /settings like this. But still I am confused why <AppContext.Provider get rerendered.
Cynipid gall wasp
would u share ur code for better understanding.
@Varun im managing auth with a global context and when I relaod user gets signed out
Cynipid gall wasp
for only auth using redux is overkill.
ok
yea im doing auth with firebase
and im just setting a context with the authuser but that gets removed on reload
and idk how secure it is
cookies are prob the way
so the general structure with that is
on signin get cookie from firebase and set it
and send cookie with all future api reqs?
and on signout get rid of cookie?
on signin get cookie from firebase and set it
and send cookie with all future api reqs?
and on signout get rid of cookie?
in my api how do I like verify the cookie?
like will there be firebase func to like check if that cookie is a legit user?
@Varun like will there be firebase func to like check if that cookie is a legit user?
Cynipid gall wasp
user logs in with fb
fb gives a session cookie
save the fb cookie on the user's device
send cookie with requests and verify with auth sdk firebase-admin and perform ur step
delete the saved cookie when the user logs out
fb gives a session cookie
save the fb cookie on the user's device
send cookie with requests and verify with auth sdk firebase-admin and perform ur step
delete the saved cookie when the user logs out
I did some research and
// pages/AuthenticatedPage.js
import nookies from 'nookies';
import { verifyIdToken } from '../utils/auth'; // Path to your verifyIdToken function
export async function getServerSideProps(context) {
try {
const cookies = nookies.get(context);
const token = cookies.token; // Adjust this if your token is stored under a different name
// Verify the token using your utility function
const decodedToken = await verifyIdToken(token);
const email = decodedToken.email; // Extract email from the decoded token
// Continue with your server-side logic, if the token is verified, the email is available
return { props: { email } };
} catch (error) {
// If there's any error (token invalid, expired, etc.), redirect to login page or return an error
return {
redirect: {
destination: '/login',
permanent: false,
},
};
}
}
const AuthenticatedPage = ({ email }) => {
// You can now use the email in your component
return (
<div>
<p>Authenticated as: {email}</p>
{/* Your authenticated route content */}
</div>
);
};
export default AuthenticatedPage;gpt is telling me to do smthn like this to get the email from the token
would this work if my files have 'use client' at the top
does that mean I cant use serversideprops
@Cynipid gall wasp would u share ur code for better understanding.
Black-chinned SparrowOP
ya sure here is the sample code
and I am trying to access the state value using context API in another page in
reason I use
// app/layout.tsx
'use client'
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const [myState, myDispatch] = useReducer(useMyReducer, initialMyState);
return (
<html lang="en" suppressHydrationWarning>
<body>
<MyContext.Provider value={{ myState, myDispatch }}>
<NextUIProvider>
<main>
{children}
</main>
<footer>
Footer
</footer>
</NextUIProvider>
</MyContext.Provider>
</body>
</html>
);
}and I am trying to access the state value using context API in another page in
app folder// app/settings/page.tsx
'use client'
export default function SettingsPage() {
const { myState } = useMyContext();
return (
<>
<UserSettings userName={myState.email} />
</>
);
}reason I use
use client is, I export the application using output: 'export' in next.config.mjs.