Home > other >  Error/Crash when react project page is refreshed but not on initial page load
Error/Crash when react project page is refreshed but not on initial page load

Time:10-20

so I am building a React Firebase Notes App I designed a profile page but I keep getting blank screen/error in the console when I refresh the page but as the GIF shows I don't get the error on initial load and the page functions just fine. I am not exactly what is causing the error so any help on how to fix it would be appreciated. Thank you.

Error message:

react-dom.development.js:26923 Uncaught TypeError: Cannot read properties of undefined (reading '0')
The above error occurred in the <Profile> component:

My code in the profile component:

function Profile() {
  const { user } = useContext(AppContext);
  const navigate = useNavigate();
  useEffect(() => {
    if (!user) {
      navigate('/');
    } else {
      navigate('/profile');
    }
  }, []);

  return (
    <m.div className="flex flex-col items-center justify-center gap-8 p-5" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
      <UpdateName />
      {user?.providerData[0]?.providerId === 'password' ? (
        <>
          <UpdateEmail />
          <UpdatePassword />
        </>
      ) : (
        <></>
      )}
      <Logout />
      <DeleteAccount />
    </m.div>
  );
}

export default Profile;

Snippet of my router code:

 <AppProvider>
      <LazyMotion features={domAnimation}>
        <div className="App">
          <main>
            <AnimatePresence mode="wait">
              <Routes location={location} key={location.pathname} initial={true}>
                <Route
                  path="/profile"
                  element={
                    <React.Suspense fallback={<Spinner />}>
                      <Profile />
                    </React.Suspense>
                  }
                />
              </Routes>
            </AnimatePresence>
          </main>
          <ToastContainer />
        </div>
      </LazyMotion>
    </AppProvider>

GIF of The Error

CodePudding user response:

It seems that user.providerData is an undefined array reference. You should use the Optional Chaining operator on the providerData array access as well.

Example:

user.providerData?.[0]?.providerId === 'password'
  • Related