vercel / next.js

The React Framework
https://nextjs.org
MIT License
126.78k stars 26.95k forks source link

On refereshing the page redirect to the homepage automatically #65198

Closed Saini-Gaurav closed 6 months ago

Saini-Gaurav commented 6 months ago

Link to the code that reproduces this issue

https://github.com/Saini-Gaurav/E-Commerce

To Reproduce

  1. Start the Application in development mode (npm run start);
  2. Suppose I am on a page Shop when i refresh the browser it automatically redirect me to the homepage

Current vs. Expected behavior

I want to be on the same page or url on refereshing the browser instead redirecting to the homepage or "/" url

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10 Pro
  Available memory (MB): 7568
  Available CPU cores: 2
Binaries:
  Node: 20.10.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.2.1 // There is a newer version (14.2.3) available, upgrade recommended!
  eslint-config-next: N/A
  react: 18.2.0
  react-dom: 18.2.0
  typescript: N/A
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Not sure

Which stage(s) are affected? (Select all that apply)

next dev (local)

Additional context

No response

JesseKoldewijn commented 6 months ago

Hey there! I just had a look in the provided repo and found the reason for the redirect behavior. It's because of the following useEffect in your Header.js:

    useEffect(() => {
        if (auth) {
            const unsubscribe = onAuthStateChanged(auth, (user) => {
                if (user) {
                    const { uid, email, displayName } = user;
                    dispatch(
                        addUser({
                            uid: uid,
                            email: email,
                            displayName: displayName,
                        })
                    );
                    setIsLoggedIn(true);
                    console.log("User is signed in, about to redirect");
                    router.push("/");
                } else {
                    dispatch(removeUser());
                    setIsLoggedIn(false);
                    router.push("/Login");
                }
            });

            return () => {
                // Clean up the subscription when component unmounts
                unsubscribe();
            };
        }
    }, [auth]);

You might want to change this specific behavior in there. Hope this helped! 👍