Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show a spinner while waiting for onAuthStateChanged() to resolve after signInWithRedirect()

I’m trying to set up a spinner, when the auth is changed. I’ve tried using the following method. (If spinner is true, it replaces the whole router component)

function App() {
  const [currentUser, setCurrentUser] = useState(false);
  const [spinner, setSpinner] = useState(false);

  useEffect(() => {
    setSpinner(true);
    onAuthStateChanged(auth, (user) => {
      if (user) {
        setCurrentUser(user);
        setSpinner(false);
      } else {
        setCurrentUser(false);
      }
    });
  }, []);

  return (
    <Context.Provider value={{ db, auth, currentUser, setSpinner }}>
      {spinner? (
        <Spinner />
      ) : (
        <BrowserRouter>
          <Navbar></Navbar>
          <Routes>
            <Route
              path='/'
              element={currentUser ? <MessageCenter /> : <Landing />}
            />
          </Routes>
        </BrowserRouter>
      )}
    </Context.Provider>
  );
}

export default App;

The problem I am facing here is, that on the first reload, the spinner doesn’t show up but if I reload my page again, the spinner shows (as it is placed in use effect, in app.js) the onAuthStateChanged is supposed to be called each time the application is loaded (To set the currentUser, On logout or login) so for that, I’m using it in useEffect on the app.js.

Is there a way to show spinner while waiting for onAuthStateChanged?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want the spinner to show right after loading, did you consider giving it a default of true?

const [spinner, setSpinner] = useState(true); // 👈 set default to true

To hide the spinner:

onAuthStateChanged(auth, (user) => {
  setSpinner(false); // 👈 move this outside of the conditional
  if (user) {
    setCurrentUser(user);
  } else {
    setCurrentUser(false);
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading