I have a simple list made in React with creation/delete/update function. I have a problem in the update, where when I modify the input, the input changes the value, but in the console.log I see the same array updating with no changes made.
Normally after the update the new list should be updated with the new changes, which is not the case. Instead in the new array, I have name: undefined Did I miss something ?
import React, { useEffect, useState } from "react";
import { v4 as uuidv4 } from "uuid";
export default () => {
const initialList = [
{
id: "a",
name: "John",
},
{
id: "b",
name: "Eric"
},
{
id: "c",
name: "Jonathan"
},
];
const [list, setList] = React.useState(initialList);
const [name, setName] = React.useState("");
function handleChangeUpdate(id) {
const newList = list.map((item) => {
if (item.id === id) {
const updatedItem = {
...item,
};
return updatedItem;
}
return item;
});
setList(newList);
console.log(newList);
}
return (
<div>
<ul >
<div>
{list.map((item) => (
<li key={item.id}>
<input className="form-control" onChange={()=> handleChangeUpdate(item.id)} defaultValue={item.name}></input>
</li>
))}
</div>
</ul>
</div>
);
};