'Update object in array using useState and a button
I have a list of users That I want to maintain, I was able to delete a user from the list and add a new user to the list, But I can not update an existing user.
import {useState} from 'react'
const ChildComp = ()=> { const [users,setUsers] = useState([{name:"Leanne " ,age : "40", city : "Gwenborough",}, {name:"Ervin " ,age : "35", city : "Wisokyburgh",}, {name:"Clementine " ,age : "22", city : "McKenziehaven",}])
const [user,setUser] = useState({name : "" , age : 0, city :""})
const [deletUser,setDeletUser] = useState ("")
const deletMe =() =>
{
let array = [...users]
let index = array.findIndex(item=>item.name===deletUser)
if (index!==-1)
{
array.splice(index,1)
setUsers(array)
}
}
const Update = (e) =>
{
let array = [...users]
let index = array.findIndex(item=>item.name===deletUser)
if (index!==-1)
{
array.splice(index,1)
setUsers(array)
setUsers([...users,user])
}
}
return(<div>
<h1>add user </h1>
Name : <input type ="text" onChange = {e=> setUser({...user,name:e.target.value})}/><br/>
Age : <input type ="text" onChange = {e=> setUser({...user,age:e.target.value})}/><br/>
City : <input type ="text" onChange = {e=> setUser({...user,city:e.target.value})}/><br/>
<input type = "button" value ="Add" onClick ={e=>setUsers([...users,user])}/>
<input type ="button" value = "Update" onClick = {Update}/><br/>
<h3>Delet user </h3>
<input type = "text" name = "dleteUser" onChange = {e=>setDeletUser(e.target.value)}/>
<input type ="button" value = "DELET" onClick = {deletMe}/><br/>
<table border = "1">
{users.map((item,index) =>
{
return <tr key = {index}>
<td > {item.name} </td>
<td > {item.age} </td>
<td > {item.city} </td>
</tr>
})}
</table>
</div>
)
} export default ChildComp;
Solution 1:[1]
You can update a user by first getting the index of this user in the array, then update the element in the array, then return the array :
const update = (e) => {
setUsers(users => {
const index = users.findIndex(item => item.name === user.name);
if (index === -1) {
return […users, user];
}
users[index] = user;
return users;
}
}
Solution 2:[2]
You use "deletUser" within your Update function although that variable is only set when clicking the "DELET"-Button. What you want to use is the user-variable that is set whenever you're changing one of the upper input-fields.
Here's some example code that updates a user entry
const Update = () => {
setUsers(
users.map((existingUser) => {
return existingUser.name === user.name
? user
: existingUser;
})
);
};
p.s.: As your input-strings are suffixed with a space ("Leanne ") you would have to write "Leanne " in your input field to change the first entry.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lukas Laudrain |
| Solution 2 | Andreas.Ludwig |
