Created
December 16, 2020 16:25
-
-
Save himat/593eb4f6c6a47cb5a2c7c3bb9d52da8e to your computer and use it in GitHub Desktop.
[Update element in react state array] #react
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackoverflow.com/a/46761122/1807163 | |
const [employees, setEmployees] = useState([]); | |
const onUpdate((newEmployee) => { | |
setEmployees((existingEmployees) => { | |
const index = employees.findIndex(emp => emp.id === newEmployee.id); | |
const newEmployees = [...existingEmployees]; // important to create a copy, otherwise you'll modify state outside of setState call | |
newEemployees[index] = employee; | |
return newEmployees; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment