Forced refresh is a consequence of accessing undefined paths or error pages in Next.js
P粉254077747
P粉254077747 2024-04-05 08:32:46
0
1
510

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粉254077747
P粉254077747

reply all(1)
P粉511749537

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);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template