Uncaught TypeError: Cannot read properties of null (reading 'uid') : Get this error but application work fine?

Viewed 259

I get this error upon logging out: (Uncaught TypeError: Cannot read properties of null (reading 'uid')), but my application works and does what I want it to do.

Within my logout function I am basically deleting an API access token from the user doc in the database when user logouts, because the token does not expire so it is added on login and removed on logout as part of authentication process. This all works fine.

so how do I get rid of this error, is there another way I can structure my code to get rid of this error?

It makes sense that this error appears once user has logged out because the uid is longer available to access due to user not being active (current user).

Many thanks, code below.

import { signOut } from "@firebase/auth";
import { useNavigate } from "react-router";
import { auth, db } from "../../firebase";
import { doc, updateDoc, deleteField } from "firebase/firestore";




export const Logout = () => {
    const user = auth.currentUser;
    const uid = user.uid;
    console.log(uid);
    const userRef = doc(db, 'users', uid);
    const navigate = useNavigate();



    const logoutUser = async () => {
        //Deleting mavenlink access token
        await updateDoc(userRef, {
            accessToken: deleteField()
        });

        signOut(auth).then(() => {
            navigate("/")
        })
    }

    return {logoutUser}
};

For context below is code where authenticated routes are handled in app.js

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [state, setState] = useState({});
  const [user, loading, error] = useAuthState(auth);
  
  //Hook to handle authentication
  useEffect(() => {
    if (loading) {
      // maybe trigger a loading screen
      return;
    }
    if (user && !isAuthenticated){ 
      setIsAuthenticated(true);
      console.log("logged in");
    } else if (!user && isAuthenticated) {
      setIsAuthenticated(false);
      console.log("logged out");
    }
  }, [user, loading]);

  const unauthenticatedRoutes = useRoutes([
    { path: "/", element: <LoginForm/> },
    { path: "/reset", element: <ResetForm/> },
    { path: "/register", element: <RegisterForm/> },
  ]);

  return (
    <AppContext.Provider value={{
        isAuthenticated, setIsAuthenticated, 
    }}>
        <div className="App">
            {!isAuthenticated ? <>{unauthenticatedRoutes}</> : <Sidebar/>}
        </div>
    </AppContext.Provider>
  );
}

export default App;

Note: the authenticated routes are defined in the sidebar component and rendered there.

1 Answers

You may add privateRoutes to resolve this issue. What I mean by this is create a file where you specify the condition whether your component should be rendered, or it should redirect to signin page. And you can convert your normal route to private route. wrap your element in private route in your normal route. When you make your signout function a private component it will redirect the user to signin page as now user is deleted and currentUser no longer exist.

import React from 'react';
import { Navigate} from 'react-router-dom';
//import user from firebase

export default function PrivateRoute({ children }) {
  const { currentUser } = // user imported
  return currentUser ? children : <Navigate to="/signin" />;
}
Related