简体   繁体   中英

Firebase Authentication using React - issue with page refresh

I am trying to create a basic React app with Firebase and Zustand. There is a login page and a dashboard page. You can only view the dashboard page if you are logged in otherwise you get redirected to login page. After logging in, the user is redirected to dashboard page which displays user email id. The problem is when I refresh the dashboard page after logging in, in spite of being logged in, I get redirected to login page because in the first render,username is null.Code is attached. How can I get around this behavior?

function App() {
  const userData = useUserStore((state) => state.setUser);
  useEffect(() => {
    const authState = onAuthStateChanged(auth, (user) => {
      if (user) {
        userData(user.email);
      } else {
        console.log("no user");
      }
    });

    return () => {
      authState();
    };
  }, []);

  return <RouterProvider router={router} />;
}
function Dashboard() {
  const username = useUserStore((state) => state.username);

  return username ? (
    <div>Hi, {username}</div>
  ) : (
    <Navigate to="/login" />
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM