Nina
Nina

Reputation: 509

React: Mapping an array of data

I am trying to map data that I have in an array, however, the data is not mapped when I run the code. If I log the data (serials variable), it logs the variables that I would like to map (screenshot below). Does anyone have any suggestions about why the data isn't mapped?

numberList() {
  const uid = this.state.user.uid;
    const serialRef = db.ref(uid + "/serials");
    
    serialRef.on("value", (serial_numbers)=> {
      const serials = [];
      serial_numbers.forEach((serial_number)=> {
        serials.push({s:serial_number.val()});
      });
      console.log(serials);
  return (
    <ul>
      {serials.map((number) => <li>{number}</li>)};
    </ul>
  );
    });

}
        render (){
        return (
          <button onClick={this.numberList}>Cards</button>
        )};

}

Screenshot of the data

Thanks in advance!

Upvotes: 1

Views: 251

Answers (2)

Faire
Faire

Reputation: 1021

The "numbers" you are mapping are objects (according to the log you attached), but React JS doesn't allow to display objects directly - you probably only want to display the value anyway. You should also include a key when generating a view from an array of objects. The correct code should be this:

<ul>
      {serials.map((number, i) => <li key={i}>{number.s.serial}</li>)};
</ul>

Upvotes: 1

tuhin47
tuhin47

Reputation: 6068

From your log I assume the map should be as below to get exact number.

 return (
    <ul>
      {serials.map((number) => <li>{number.s.serial}</li>)};
    </ul>
  );

Upvotes: 1

Related Questions