TypeError: Cannot read properties of null (reading 'uid')

41 Views Asked by At

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 (
  ...
  );
};

1

There are 1 best solutions below

3
Folyik On

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 currentUser is null when trying to call OnSnapshot

To fix this you can simply check if currentUser is not null or undefined inside that useEffect and update the dependency array to use a nullable object :

 useEffect(() => {
    if(currentUser !== null && currentUser !== undefined)
    {  
      const unsub = onSnapshot(doc(db, "userChats", currentUser.uid), (doc) => {
              setUserChats(doc.data());
              setLoading(false);
            });
        
      return () => unsub();
    }
  }, [currentUser?.uid]);