Home > Software design >  Mapping an array of id and fetching relevant data from an external api
Mapping an array of id and fetching relevant data from an external api

Time:01-04

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?

CodePudding user response:

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.

CodePudding user response:

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

  •  Tags:  
  • Related