Want
I want my next application to hit the endpoint /api/users/whoami
which basically validates the cookie and returns the payload of the user logged in
Have
I am using ContextApi
to set the authState
in my application.
The issue is, all this logic is in _app.js
file's useEffect
which is OUTSIDE <AuthContextProvider>
Thus, I am unable to set the state (context) from inside of _app.js
:
function MyApp({ Component, pageProps }: AppProps) {
const { setAuthState, authState } = React.useContext(AuthContext);
React.useEffect(() => {
const whoAmI = async () => {
const { data } = await api.get(AuthEndpoints.whoami);
if (data) { // setting state
setAuthState({ isAuthenticated: true, userId: data.id, username: data.username });
} else {
setAuthState({ isAuthenticated: false, userId: null, username: null });
}
};
whoAmI();
}, [Component]);
console.log(authState); // This wont update
return (
<AuthContextProvider> //
<QueryClientProvider client={queryClient}>
<Navbar />
<Component {...pageProps} />
</QueryClientProvider>
</AuthContextProvider>
);
}