简体   繁体   中英

Firebase Auth user is logged out on every page refresh - React

Every time the page is refreshed the user is sent back to the login screen after authentication. I am using the onAuthStateChanged listener, however, after the page is refreshed it acts like there was no authenticated user to begin with.

  const dispatch = useDispatch();
  const currentUser = useSelector((state) => state.user.value);
  useEffect(() => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        dispatch(setCurrentUser({ email: user.email, uid: user.uid }));
        console.log("user", user.email);
      }
    });
  }, []);
  return currentUser.email ? <LoggedIn /> : <Welcome />;
}
  const dispatch = useDispatch();
  const currentUser = useSelector((state) => state.user.value);
  useEffect(() => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        dispatch(setCurrentUser({ email: user.email, uid: user.uid }));
        console.log("user", user.email);
      }
    });
  }, [currentUser]);
  return currentUser?.email ? <LoggedIn /> : <Welcome />;
}

maybe, that would help. just add currentUser to the second argument array

I know that onAuthStateChanges() method is asynchronus. So just move rediraction inside this method.

  const dispatch = useDispatch();
  const currentUser = useSelector((state) => state.user.value);
  useEffect(() => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        dispatch(setCurrentUser({ email: user.email, uid: user.uid }));
        console.log("user", user.email);
        openRoute(<LoggedIn />)
        return
      }
      openRoute(<Welcome />)
    });
  }, []);
}

This function triggers whenever auth state changes so if you log out you wanna back to login page and this way will work.

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