PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

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

 October 14, 2022     async-await, asynchronous, axios, javascript, reactjs     No comments   

Issue

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

Solution

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


Answered By - Nick
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing