skip to Main Content
const page = () => {
  const router = useRouter();
  const {data, isLoading} = useGetUser();
  
  useEffect() => ({
    if (isLoading) return;
    if (!data) {
      router.push('/create-account');
    }
  }, [isLoading, data])
  
   if (isLoading) {
    return <spinner />
   }
   
   return (
    <Home />
   )
}

I need to redirect to the create-account page if a user is not authenticated.
The above code works well. But it redirects to create-account page when I navigate the home page after signing in.
I debugged and I found the isLoading and data will be false together when the page is loading the first time.

Is there any way to prevent this?

3

Answers


  1. useEffect() => ({
        if (!loading){
           if (!data) {
             router.push('/create-account');
           }
        }
      }, [loading, data]) // on loading completed
    

    This will resolve your issue

    Login or Signup to reply.
  2. The answer from @Muammad Ahab should work, but you can use a React hook as well:

    import { useState, useEffect } from 'react';
    import { useRouter } from 'next/router';
    import { useGetUser } from 'path/to/custom/hook';
    
    const Page = () => {
      const router = useRouter();
      const { data, isLoading } = useGetUser();
      const [hasMounted, setHasMounted] = useState(false);
    
      useEffect(() => {
        setHasMounted(true);
      }, []);
    
      useEffect(() => {
        if (hasMounted && !isLoading && !data) {
          router.push('/create-account');
        }
      }, [hasMounted, isLoading, data, router]);
    
      if (isLoading) {
        return <Spinner />;
      }
    
      return <Home />;
    };
    
    export default Page;
    
    
    Login or Signup to reply.
  3. Have you tried using useLayoutEffect hook? This hooks runs before the page is painted.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search