简体   繁体   中英

React Native: Retrieved data from firestore in async function is being deleted

I am building a react native application and am interacting with Firebase, more specifically Firestore. I am using a functional component and am attempting to retrieve data when the component mounts. I want to store this data as objects in an array, which I will later use to display in a flatlist. The code I am using to do so can be seen below:

const [myData, setMyData] = useState([]);

const app = props => {

   useEffect(() => {
       async function getData() {
         await firebase
           .firestore()
           .collection("data")
           .where("data_name", "==", "name")
           .get()
           .then((snapshot) => {
             snapshot.forEach((doc) => {
             let jsonObj = {
                date: doc.data().date,
                language: doc.data().lang,
                ... (more data)
             };
              setMyData([...myData, jsonObj]);
          });
        });
      }
    getData();

  }, []);


  ...
}

The query that I wrote works correctly and I am able to get the data I am looking for. However, after putting all of the jsonObj into my array using setMyData , I am only left with one object in my array after everything finishes executing. The only object in the array myData that is left at the end is the one that was last added to it. Every other object that was added before seems to have gotten deleted somehow. Why is this happening?

You only see last item because your state updating every time and replaces existing data with new item.

You need to create an array that holds all data and then setMyData outside of that forEach loop.

Try something like this:

   useEffect(() => {

           async function getData() {
    let arr = [];
             await firebase
               .firestore()
               .collection("data")
               .where("data_name", "==", "name")
               .get()
               .then((snapshot) => {
                 snapshot.forEach((doc) => {
                 let jsonObj = {
                    date: doc.data().date,
                    language: doc.data().lang,
                    ... (more data)
                 };
               arr.push({...myData, jsonOb})
              });
                  setMyData(arr);
            });
          }
        getData();
    
      }, []);

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