Home > Back-end >  how to await axios call within .map that is inside of useEffect React
how to await axios call within .map that is inside of useEffect React

Time:07-15

Inside of my useEffect hook I am trying to call an api request that is inside of .map but the rest of the function isn't waiting for the response. I've tried making the .map async but then the rest of the function returns Promises what is the correct way of doing this so that my api request can be called and then proceed with the rest of the code?

const getData = async (id) => {
    const myData = await api.get(
      '/api/request/id'
    );
    return myData;
  };

useEffect(() => {
  const myData = sampleData.map((item)
    getData(item.id).then((response) => {
      console.log(response.data.data);
      return response.data.data
    })
  
  const myThings = myItem.things.map((thing) => {
    if (thing.type === 'sampleType1') {
      return [thing.name, thing.value];
    } else (thing.type === 'sampleType2') {
      return [
        thing.name,
        thing.content.name,
      ];
    }
  });
  setData = {myThings, myData}
}, []);

CodePudding user response:

You are going to want to wait for all those promises to resolve before mapping over them, so this is a great use case for Promise.all:

useEffect(() => {
  async function fetchData() {
    const myData = await Promise.all(sampleData.map((item) =>
      getData(item.id).then((response) => {
        console.log(response.data.data);
        return response.data.data
      }));
  
    const myThings = myItem.things.map((thing) => {
      if (thing.type === 'sampleType1') {
        return [thing.name, thing.value];
      } else (thing.type === 'sampleType2') {
        return [
          thing.name,
          thing.content.name,
        ];
      }
    });
    setData = {myThings, myData}
  }
  
  fetchData();
}, []);
  • Related