0

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>
  );
}
Karan Kumar
  • 2,678
  • 5
  • 29
  • 65
  • hi, check this link https://stackoverflow.com/questions/60899880/next-js-reduce-data-fetching-and-share-data-between-pages – Abhilash CR Jan 24 '22 at 13:50
  • Move this `useEffect` inside the Context itself – Melvynx Jan 24 '22 at 15:04
  • But I want to add "Component" to the dependency array of the `useEffect` so that this request is made everytime the page is changed. Can I pass down the component itself to `` as a prop and use it there? Would that be ideal? – Karan Kumar Jan 24 '22 at 18:00

0 Answers0