search

Home  >  Q&A  >  body text

Forced refresh is a consequence of accessing undefined paths or error pages in Next.js

Accessing an undefined path or error page causes Next.js to do a hard refresh, causing my context to go back to its default state (i.e. the value stored in the userProfile state variable becomes null)

I have a layout using {stucture: Sidebar and main} and in the Sidebar component I display the user email which I get from the context hook as a state variable.

However, when I click on an undefined path or enter manually in the URL, I get a custom error page thrown back to the index page ('/'), but due to this I lose my The status returns to null(context).

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 set my status (on success) in the login handler of the login page.

Is there any workaround or should I use local storage

Currently, when he goes back to the index page, I get the user profile again.

I think local storage might be a better option.

P粉254077747P粉254077747261 days ago584

reply all(1)I'll reply

  • P粉511749537

    P粉5117495372024-04-06 00:57:57

    I solved my problem by only setting the state in the context file and not anywhere else. In short, I get the user's profile data in the context.js file and set the state there so it can be used everywhere. If anyone has the same problem, please mention me!

    My context.js file looks like below

    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 (
        
          {children}
        
      );
    }
    
    export function useUserContext() {
      return useContext(UserContext);
    }

    reply
    0
  • Cancelreply