Trytobegood
Trytobegood

Reputation: 7

Using ._id from mongodb as key form components in React js

Each entry in mongodb has a unique id, I am using this id for the Key property in my components to resolve this error:

Warning: Each child in a list should have a unique "key" prop.

Suppose we have an input field that you can enter a text to be added to the database and a table that shows the database. When you add something to the database, you can see the added item.

  const handleSubmit = (e) => {
    e.preventDefault();
    const code = e.target.elements['code'].value;

      addToDB(code);
      setDataFromDB([...dataFromDB, { code}]);
    
  };

Here I'm updating the state of the datafromDB to see the changes. The problem is since we do not assign any id to the new input in this step, it does not have any id which cause this error: Warning: Each child in a list should have a unique "key" prop.

{dataFromDB &&
          dataFromDB.map((el) => {
            return <CodeComponent key={el._id} el={el} />;
          })}

Actually it should go to the database and then the mongodb assign it a new unique id. That's why in the initial render with the pre stored items in database I do not have this problem.

What should I do?

Upvotes: 0

Views: 598

Answers (1)

Tobok Sitanggang
Tobok Sitanggang

Reputation: 620

i guess, you are using insertOne and it will always return data like

{
   "acknowledged" : true,
   "insertedId" : ObjectId("uniqueId")
}

To do this, you need to update the code.

For example:

const handleSubmit = (e) => {
    e.preventDefault();
    const code = e.target.elements['code'].value;

    // Add to the database
    const dbResponse = addToDB(code);

    // Get the unique id from the database response
    const _id = dbResponse.insertedId;

    // Update the state of the datafromDB
    setDataFromDB([...dataFromDB, { code, _id }]);
};

{dataFromDB &&
    dataFromDB.map((el) => {
        return <CodeComponent key={el.id} el={el} />;
    })
 }

Upvotes: 0

Related Questions