Home > OS >  Why is an array of documents taken from an async function empty even if I loaded it?
Why is an array of documents taken from an async function empty even if I loaded it?

Time:12-07

I load an array of documents using an async function. If I print in the console the array.length this value result 0, but if I print the array I can see all the values, and they seems correctly loaded.

const array = [];

async function getArray() {
  const arraySnaps = await getDocs(collection(db, "CollectionName"));

  for(var i = 0; i < arraySnaps.docs.length; i  ){
      arrayList[i] = arraySnaps.docs[i].data();
  }

  return array;
}
getArray();
console.log(array.length);
console.log(array);

This is a problem because I can not use the values in other parts of code, because the array result empty.

If you need I can also post the two logs.

CodePudding user response:

You have to use the useEffect hook, to be able to fetch your data once your component has been mounted, and store this data in the state of your component:

  export default function App() {
    const [array, setArray] = useState([]);
    useEffect(() => {
      async function getArray() {
        // Fetch asynchronously the data
        const arraySnaps= await getDocs(collection(db, "CollectionName"))
        // Get the needed info from them
        const array = arraySnaps.docs.map(doc => doc.data())
        // Store it in the local state of our component
        setArray(array);
      }
      // This function is called one time, once the component is mounted
      getArray();
    }, []);
    // Initialy, array is an empty array, and once we fetched the data, the component will be rerended with the fetched array
    console.log(array.length);
    console.log(array);
}
  • Related