Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda