Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
Mapping an array of id and fetching relevant data from an external api

I am trying to map an array of id and fetch relevant data for that id from an external API in React. Here is my code:

const getDetails = async () => {
      ids.map(async(id) => {
        const details = await axios.get(`url/${id}`);
        setIdDetails(details);
      });
    };
getDetails();

And trying to display those details in a dropdown menu like this:

{idDetails.map((detail) => {
     <MenuItem value={detail}>{detail.data.title}</MenuItem>
})}

I get the error that idDetails.map is not a function. Also, I tried pushing to the array instead of setting state, no luck either. I have this feeling that I am doing the whole data fetching thing wrong. What is the best practice to handle a situation like this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Just use setIdDetails([...idDetails, details]); to push the new data into the array.

const [idDetails, setIdDetails] = useState([]);

const getDetails = async () => {
  ids.map(async(id) => {
    const details = await axios.get(`url/${id}`);
    setIdDetails([...idDetails, details]);
  });
};
getDetails();

Also, make this change to avoid data specific error

{(idDetails || []).map((detail) => {
     <MenuItem value={detail}>{detail?.data?.title}</MenuItem>
})}

Note: I am hoping that you are getting details as an object here const details = await axios.get(url/${id});

about 4 years ago · Juan Pablo Isaza Report

0

As mentioned by @SurjeetBhadauriya, use the spread syntax setIdDetails([...idDetails, details]);.

This will push the buffer after spreading it as single items, which will allow you to map them in your jsx.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!