简体   繁体   中英

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?

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});

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.

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