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.