简体   繁体   中英

how to await axios call within .map that is inside of useEffect React

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

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

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