Muhammad Hossam
Muhammad Hossam

Reputation: 65

Next.js with firebase onAuthStateChanged

function useAuth() {
  const [user, setUser] = useState('');

  useEffect(() => {
    auth.onAuthStateChanged(function handleAuth(user) {
      if (user) {
        setUser(user);
      } else {
        setUser(null);
      }
    });
  }, [user]);

  return user;
}



import useAuth from '../components/useAuth';
function MyApp({ Component, pageProps }) {
  const user = useAuth();

  return (
    <Fragment>
      <Head>
        <title>whatsapp</title>
        <meta name="description" content="whatsapp by create next app" />
        <link rel="icon" href="\whatsapp--v1.png" />
      </Head>
      {!user ? <Login /> : <Component {...pageProps} />}
    </Fragment>
  );
}

I want to check if there is a user then go to a login.js page , if not go to index.js. But there is a problem: the user becomes null in the beginning then have a value, and this results in a delay that makes the login page always appear first for one second then index page even if there is a user. How to make the render after the user data fully loaded?

Upvotes: 1

Views: 3291

Answers (1)

Elvaleryn
Elvaleryn

Reputation: 351

You can define a loading state and render it when you fetch the data something like this it should be:



function useAuth() {
  const [user, setUser] = useState('');
  const [loading, setLoading] = useState(false);
  
  useEffect(() => {
    setLoading(true)
    auth.onAuthStateChanged(function handleAuth(user) {
      if (user) {
        setUser(user);
        setLoading(false);
      } else {
        setUser(null);
        setLoading(false)
      }
    });
  }, [user]);

  return {user, loading};
}



import useAuth from '../components/useAuth';
function MyApp({ Component, pageProps }) {
  const auth = useAuth();
  if(auth.loading) return 'loading...'
  return (
    <Fragment>
      <Head>
        <title>whatsapp</title>
        <meta name="description" content="whatsapp by create next app" />
        <link rel="icon" href="\whatsapp--v1.png" />
      </Head>
      {!auth?.user ? <Login /> : <Component {...pageProps} />}
    </Fragment>
  );
}

Upvotes: 2

Related Questions