Warning: Encountered two children with the same key, `[object Object]`

Viewed 165

i am trying to run this code and getting error my code is as below in this useState hook i have a array and i am trying to loop through it but only thing i am getting is error

import React, { useState } from "react";

const LoadAllUser = () => {
  const [users, setUsers] = useState([
    {
      name: "Bhoomit",
      email: "bhumit070@gmail.com",
    },
    {
      name: "Bhopu",
      email: "bhopu@gmail.com",
    },
    {
      name: "sameer",
      email: "sam@gmail.com",
    },
  ]);

  return (
    <div>
      {users !== undefined && users.length > 0 ? (
        users.map((index, user) => {
          return (
            <div className="" key={index}>
              {user.name} <br />
              {user.email} <br />
            </div>
          );
        })
      ) : (
        <h1> No users found </h1>
      )}
    </div>
  );
};

export default LoadAllUser;

1 Answers

The problem is that the variables have the values of the other.

This is how the data looks like if you show it in console:

index: {"name":"Bhoomit","email":"bhumit070@gmail.com"}
user: 0
index: {"name":"Bhopu","email":"bhopu@gmail.com"}
user: 1
index: {"name":"sameer","email":"sam@gmail.com"}
user: 2

So the keys are [object Object] and for react that is the same. And you cannot have same keys.

So you need to change places of index and user... like this:

users.map((user, index) => {}
Related