0

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

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

bless you, its work dude and not blank white again.
1

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

1 Comment

oh w8, "Uncaught TypeError: Cannot read properties of undefined (reading 'map')" and blank white
0

I think You should return the paragraph tag

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

2 Comments

Blank white, and "Uncaught TypeError: Cannot read properties of undefined (reading 'map')"on the line listCategory[0].map
what does it shows you when you do console.log(listCategoty); ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.