Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading