简体   繁体   English

在 React 本机 useEffect 中,使用异步调用我得到一个未定义的,在以下情况下如何避免未定义?

[英]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.这些是我在 UseEffect 中使用的调用,由于短暂的延迟,我在 TAGID 中未定义,后来我在 setState 中获取数据和设置。现在问题是下一个我调用 firebase,它存储了一个未定义的文档在 Firestore 数据库中,以避免 firebase 调用的未定义或任何其他方法。 How to call the Firestore call in the useEffects or how to avoid that undefined in this case.如何在 useEffects 中调用 Firestore 调用,或者在这种情况下如何避免未定义。

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 是一个异步 function,你应该等到它完成,你可以这样做:


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在返回 promise 后,我在返回中也变得未定义

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();
    }, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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