[SOLVED] isAuthenticated` on refresh first shows `false`

Hi all,
I’m trying to manage my authenticated state of my app which starts at this studio page.

import { useEffect } from "react";
import { useRouter } from "next/router";
import { useMoralis } from "react-moralis";
import Navigation from "../../components/Navigation";

const Studio = () => {
  const { isAuthenticated } = useMoralis();
  const router = useRouter();

  useEffect(() => {
    console.log(isAuthenticated);
    if (!isAuthenticated) {
      router.push(`/login`);
    }
  }, [isAuthenticated]);

  return (
    <>
      <Navigation />
      <div className="padded-container"></div>
    </>
  );
};

export default Studio;

I have already connected my wallet but when I refresh my browser the log shows false first (which will prompt the router to the login page) and from the login page it then detects that isAuthenticated is true. This causes a little flash.

Is there a better way to handle the first load of isAuthenticated? Perhaps a loading component until it retrieves the right value?

Maybe try using user from const { user } = useMoralis();. So if there is no logged in user account it goes back to login page.

Same problem will persist. With a refresh, the `user will start as “null” which will prompt a push to /login.

Does the parent of the Studio component have an authenticated state?

Maybe you can try it this way.

const { isInitialized, isAuthenticated } = useMoralis();
  useEffect(() => {
    const isAuth = () => (!isAuthenticated ? router.push("/login") : null);
    isInitialized && isAuth();
  }, [isInitialized, isAuthenticated]);
2 Likes

This works perfectly!! Thank you!!