Home > front end >  How to map through an array, which has an array of multiple objects?
How to map through an array, which has an array of multiple objects?

Time:02-10

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.

CodePudding user response:

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>

CodePudding user response:

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.

CodePudding user response:

Use react useState / setState for this

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

  •  Tags:  
  • Related