0

I want to get data from firebase inside a useEffect function like this:

  useEffect(() => {
   /** nope */
   async function fetchData() {
     let dataObject = {};
     let dataArray = [];
     setAttendees({});

     // You can await here
     if (newData[listRedux]) {
       const request = await Object.keys(newData[listRedux] . 
       [1].attendees).map(
         user => {
           usersRef.child(user).on('value', snap => {
             dataObject[snap.key] = snap.val();
             setAttendees(dataObject);
             console.log(dataObject);
             let comp = (
               <Avatar
                 key={snap.key}
                 size="small"
                 source={snap.val().avatar}
                 alt={snap.val().name}
               />
             );
             dataArray.push(comp);
             setAttendeesComp(dataArray);
           });
         }
       );

       // Wait for all requests, and then setState
       await Promise.all(request).then(() => {
         console.log('done');
       });
     }
   }
   fetchData();
 }, [newData, listRedux]);

Now the second console.log inside the promise all will first show then the first console.log, meaning the request was not done yet. How can i improve my code so the request and the states are first being set and then continue with the rest?

Ronald Zwiers
  • 780
  • 2
  • 10
  • 25

1 Answers1

0
export default function Example() { 
    const [data, dataSet] = useState(false)
    const [attendees, setAttendees] = useState(false)

    async function fetchMyAPI() {
      let response = await fetch('api/data')
      response = await res.json()
      console.log(response);
      dataSet(response)
    }

 useEffect(() => {
      if (!attendees) return 
      fetchMyAPI();
    }, [attendees, newData, listRedux]);


useEffect(() => {
     setAttendees({})
  }, [])

More examples here:

ZiiMakc
  • 31,187
  • 24
  • 65
  • 105