Search code examples
reactjsnext.jsreact-contextnext.js13

Visiting an undefined Path or a error page results in hard reload in Next.js


Visiting an undefined Path or an error page results in a hard reload in Next.js which in turn leads to my context getting back to its default state (i.e value stored in userProfile state variable gets back to null)

I have a layout that I use {stucture: Sidebar and main}, in Sidebar Component I am displaying user email which I am getting from my context hook as a state variable.

But when I click on an undefined path or write it manually in url I throw a custom error page which goes back to index page('/'),but I am losing my state back to null (context) because of this.

my context file looks like this

import { createContext, useState, useContext } from 'react';

const UserContext = createContext();

export function UserProvider({ children }) {
  const [userProfile, setUserProfile] = useState(null);

  return (
    <UserContext.Provider value={{ userProfile, setUserProfile }}>
      {children}
    </UserContext.Provider>
  );
}

export function useUserContext() {
  return useContext(UserContext);
}

I am setting my state inside (on success)login handler on the login page.

Is there any workaround or should I use local storage for this For now, I am fetching userProfile again on index page when he transitions back to the index page. I think local storage would have been a better choice


Solution

  • I fixed my issue by not setting the state in any place but just inside the context file, so, in short, I am fetching the user's profile data inside the context.js file, and there itself I am setting the state which can be used anywhere . If someone comes across the same problem mention me!

    My Context.js file looks like this

    import { createContext, useState,useEffect, useContext } from 'react';
    
     const UserContext = createContext();
    
     export function UserProvider({ children }) {
      const [userProfile, setUserProfile] = useState(null);
      const [loading, setLoading] = useState(true);
    
     useEffect(() => {
       const fetchUserProfile = async () => {
        try {
         const res = await fetch(process.env.NEXT_PUBLIC_API_DOMAIN + '/userProfile');
           const userData = await res.json();
           setUserProfile(userData);
           setLoading(false);
      } catch (error) {
        console.error("Error fetching user profile:", error);
        setLoading(false);
      }
    };
    
     fetchUserProfile();
    }, []);
    
     return (
      <UserContext.Provider value={{ userProfile, setUserProfile,loading }}>
       {children}
     </UserContext.Provider>
     );
    }
    
    export function useUserContext() {
     return useContext(UserContext);
    }