I need to run that hook which fetch documents with currentUser.uid names but it fails. The hook starts before i get currentUser so basically it starts when the currentUser is null. Also i can't understand such behaviour.
TypeError: Cannot read properties of null (reading 'uid') Source src/layout/SideBar/index.tsx (29:22) @ SideBar
Context:
export const AuthContextProvider = ({ children }: { children: ReactNode }) => {
const [currentUser, setCurrentUser] = useState<any>(null);
useEffect(() => {
const unsub = onAuthStateChanged(
auth,
(user) => user && setCurrentUser(user)
);
return () => unsub();
}, []);
return (
<AuthContext.Provider value={{ currentUser }}>
{children}
</AuthContext.Provider>
);
};
Component:
export const SideBar = () => {
const { currentUser } = useContext(AuthContext);
useEffect(() => {
const unsub = onSnapshot(doc(db, "userChats", currentUser.uid), (doc) => {
setUserChats(doc.data());
setLoading(false);
});
return () => unsub();
}, [currentUser.uid]);
return (
...
);
};
I think what you are asking is how to update the UseEffect in Sidebar so that it doesnt error?
If that is the case, it is erroring because the
currentUseris null when trying to callOnSnapshotTo fix this you can simply check if
currentUseris not null or undefined inside thatuseEffectand update the dependency array to use a nullable object :