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

206
Visualizações
How to map through an array, which has an array of multiple objects?

I have called an api which gives me somewhat of a response like this,

manufacturers: [{,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}]
0: {,…}
1: {,…}
2: {,…}
3: {,…}
4: {,…}
5: {,…}
6: {,…}
7: {,…}
8: {,…}
9: {,…}

then I stored this in an array, which is like this (in console this gives me a single element array, which has an array of 10 elements ):

const arrOfProducts = [];

  axios
      .get(url)
      .then((response) => {
        arrOfProducts.push(response.data.result.manufacturers);
        console.log(arrOfProducts); //in console this gives me a single element array, which has an array of 10 elements 
      })
      .catch((error) => {
        console.log(error);
      });

Then I tried to map it in my React component Like this:

<Box
      display='flex'
      flexDirection='row'
      alignItems='center'
      justifyContent='space-evenly'
    >
      {arrOfProducts.map((items,index)=>{
        return <Box key={index}>{items.city}</Box>  //it has multiple keys like city,name etc
      })}
    </Box>

which doesn't render anything. Please tell me what I am doing wrong. Also please can suggest a better approach than this to store an api.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Use react useState / setState for this

function ProductList() {
  const [arrOfProducts, setArrOfProducts] = useState([]);
  
  useEffect(() => {
    axios.get("products").then(list => {
        setArrOfProducts([...arrOfProducts, ...list]);
    })
  })
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You are creating a wrapper array around the response unnecessarily, which is causing your confusion. The plain array of objects and nothing else is present in the response, so just use that.

Since you're in React, you should also be using a state setter. Something like:

const [products, setProducts] = useState([]);

useEffect(() => {
    axios
        .get(url)
        .then((response) => {
            setProducts(response.data.result.manufacturers);
        })
        .catch((error) => {
            console.log(error);
        });
}, []);

You don't need to also .push the result to another array.

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to use state to rerender the component, just pushing to the array will not re-render

do it like this if you are using functional component

import React, { useState, useEffect } from 'react';

const [item, setItems] = useState([]);

// Wrap api request in useEffect to make sure it only run once
useEffect(() => {
    axios.get(url).then((response) => {
        setItems(existingItems => [...existingItems, response.data.result.manufacturers]);
    })
    .catch((error) => {
        console.log(error);
    });
}, []);

// Render
<Box
    display='flex'
    flexDirection='row'
    alignItems='center'
    justifyContent='space-evenly'
>
    {items.map((item,index)=>{
        return <Box key={index}>{item.city}</Box> 
    })}
</Box>
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