Skip to content

Instantly share code, notes, and snippets.

@himat
Created December 16, 2020 16:25
Show Gist options
  • Save himat/593eb4f6c6a47cb5a2c7c3bb9d52da8e to your computer and use it in GitHub Desktop.
Save himat/593eb4f6c6a47cb5a2c7c3bb9d52da8e to your computer and use it in GitHub Desktop.
[Update element in react state array] #react
// 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