Home > Enterprise >  ReactJS = array mapping not showing
ReactJS = array mapping not showing

Time:02-01

I want to ask about array mapping.

So, I have data in the api that looks like this when in the console.

enter image description here

// The code for the fetch is like this

const [listCategory, setListCategory] = useState([]);

    const getListCategoryPoi = () => {
        setIsLoading(true);
        getCategoryPoi()
          .then((res) => {
            setListCategory(res[1].map((item) => item.data.features));
            console.log(res[1].map((item) => item.data.features));
            console.log(res[1].map((item) => item.data.features[0]));
          })
          .catch((reject) => {
            console.log(reject);
          })
          .finally(setIsLoading(false));
      };

// And the code to display the data like this when using .map

  {listCategory.map((item, index) => (
    <p key={index}>{item.category}</p>
  ))}

However, when I look in the browser it doesn't show up.

enter image description here

My question is, how to display the data category if the data in the console looks like the first image? Thank you

CodePudding user response:

Answering the problem in comment:

{listCategory[0]?.map(item, index) => ( 
    <p key={index}>{item.category}</p>
)}

The issue is that before fetching data from API, listCategory is empty so listCategory[0] is undefined and undefined does not have a map function

?. is optional chaining. Read here: Optional Chaining

CodePudding user response:

According to the console log, your output is like this

[
  [
    { category: 'Airport', jumlah_poi: 308 },
    { category: 'Amusement Park', jumlah_poi: 3873 },
    //... and the rest of data
  ],
];

I assume that is the value of listCategory so your code to display data will be like this

{listCategory[0].map((item, index) => (
    <p key={index}>{item.category}</p>
  ))}

CodePudding user response:

I think You should return the paragraph tag

{listCategory[0].map(item, index) => ( 
  return( 
    <p key={index}>{item.category}</p>
  ))}
  • Related