简体   繁体   中英

In React native useEffect ,using async call i am getting a undefined , How to avoid that undefined in the below case?

These are calls I am using In UseEffect due to the short delay, I am getting undefined in the TAGID, later I am getting data and setting in setState.Now the issue is next I am calling the firebase, there it was storing an undefined document in Firestore database to avoid that undefined or any other approach with firebase calls. How to call the Firestore call in the useEffects or how to avoid that undefined in this case.

useEffect(() => {
  const fetchData = async () => {
    const resData = await axios(apiURL);
    if (resData.data) {
      setTag(resData.data);
    }
  };

  fetchData();
  const TAGID = "" + tag.id + "";
  const USERID = "" + viewer.id + "";
  const tagsListener = db.doc(TAGID).onSnapshot(function (doc) {
    if (doc.exists) {
      const getData = doc.data();
      setTaginfo(getData);
    } else {
      db.doc(TAGID).set(tagSaveData);
      setTaginfo(tagSaveData);
    }
  });
  return () => tagsListener();
}, []);

fetchData is an async function, you should wait until it finishes, you can do this:


fetchData().then(tag=> {
const TAGID = "" + tag.id + "";
const USERID = "" + viewer.id + "";
const tagsListener = db.doc(TAGID).onSnapshot(function (doc) {
    if (doc.exists) {
      const getData = doc.data();
      setTaginfo(getData);
    } else {
      db.doc(TAGID).set(tagSaveData);
      setTaginfo(tagSaveData);
    }
  });
}
)

After returning promise also I am getting undefined in the return

useEffect(() => {
      const fetchData = async () => {
        const resData = await axios(apiURL);
        if (resData.data) {
          setTag(resData.data);
        }
      };
    
      fetchData().then(newTagID =>{
    if(tag){
    tag.id
    return;
    }
    })
      const TAGID = "" + newTagID.id + "";
      const USERID = "" + viewer.id + "";
      const tagsListener = db.doc(TAGID).onSnapshot(function (doc) {
        if (doc.exists) {
          const getData = doc.data();
          setTaginfo(getData);
        } else {
          db.doc(TAGID).set(tagSaveData);
          setTaginfo(tagSaveData);
        }
      });
      return () => tagsListener();
    }, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM