'onSnapshot is not working properly in useEffect hook

im working on a project on react native and im facing a bug , im trying to fetch the job of the current authenticated user which i stored in the firestore firebase ! i did that in the navigation component inside a useEffect hook so i can get the job of the current authenticated user because every job has it's own stack in the navigation ! but it's not giving me the right job i don't know why ! maybe i'm doing something wrong ? in the onSnapShot im searching for the authenticated user id in the client users if it's there then hes a client , either way hes a delivery ! but still it's not working properly ! its giving me the wrong job , i can share my screen if anyone is down to help , thank you


const [job, setJob] = React.useState("delivery");
 const userJobFromSignup = useSelector((state) => state.auth.job);

 useEffect(() => {
   onAuthStateChanged(authentication, (user) => {
     if (user) {
       setUser(user);
       const unsub = onSnapshot(
         doc(db, "users", "jobs", "client", authentication.currentUser.uid),
         (doc) => {
           if (doc.exists()) {
             setJob("client");
             console.log(job);
           } else {
             console.log(job);
           }
         }
       );
       return () => {
         unsub;
       };
     } else {
       setUser(null);
     }
   });
 }, []);


Solution 1:[1]

useEffect(() => {
  const unsub = onAuthStateChanged(authentication, (user) => {
    setUser(user);
    onSnapshot(
      doc(db, "users", "jobs", "client", authentication.currentUser.uid),
      (doc) => {
        if (doc.exists()) {
          setJob("client");
          console.log(job);
        } else {
          console.log(job);
        }
      }
    );
  });
  return unsub;
}, []);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Four