0

As I know, The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. I am having an array of objects. I want to render each item and it is working properly ! Here's the code I am using ->

<div className="itemsSection__items">
      {items &&
        items.map((item) => {
          return (
            <Item
              key={Math.random()}
              imageUrl={item.image}
              userName={item.userName}
            />
          );
        })}
    </div>

But after the items are rendered, I tried to console the items. But it only gives me an empty array ([]). So, even after the map function, how can I retrieve the items ?

Edit:

 socket.on("connect", () => {
    console.log("connected");
  });

  socket.on("newItem", (item) => {
    const newItem = JSON.parse(item);
    console.log(items)
  });

Here when I try consoling the items, it is an empty array !

Thanks !

Ajit Kumar
  • 367
  • 1
  • 10
  • 35
  • 4
    Where is the code that tries to `console.log()` the item list? – Pointy Mar 13 '21 at 12:43
  • Sounds like you are doing the logging before the items have been received – charlietfl Mar 13 '21 at 12:43
  • 2
    Can you provide a sandbox to reproduce the issue? As nothing seems to be wrong with the code you have shared. Unrelated: Using array `index` as key would be better than `key={Math.random()}`. The best would be to use some stable ID like `item.id` (if you have it). – Ajeet Shah Mar 13 '21 at 12:43
  • 2
    Code looks good, can you share the code in codesandox with where you giving console.log ? One suggestion better to use index in key , Math.random() chances for duplicate element – Sooraj Jose Mar 13 '21 at 12:55
  • Please see the updated question – Ajit Kumar Mar 13 '21 at 14:16
  • 1
    Your console log shows empty because setState is Async method. Check https://stackoverflow.com/q/30782948/2873538 – Ajeet Shah Mar 13 '21 at 16:16

0 Answers0