Reputation: 1577
I have the following state value as an array. How can I push a new list var newList
into Students
array where the key Students
is dynamically generated and sometimes it might be pushing to Teachers
array.
The current list is available at
let key = "Students"
console.log(this.state.school[key])
My state is following and I need to push the new array of students or teachers based on the key
.
this.state = {
school: {
Teachers: [
{
id: "1",
name: "T1",
},
{
id: "2",
name: "T2",
}
],
Students: [
{
id: "1",
name: "S1",
},
{
id: "2",
name: "S2",
}
]
}
}
Upvotes: 0
Views: 1413
Reputation: 265
You have to update the state in immutable way,
let oldArray = this.state.school[key];
this.setState({
school: {
[key]: [
...oldArray,
...newList
]
}
})
By this way, you can push your newList
to either Students or Teachers based on key value.
Upvotes: 1
Reputation: 1554
Check out immutability helper. https://github.com/kolodny/immutability-helper/
import update from ‘immutability-helper’;
...
const newState = update( this.state, {
school: {
[key]: { $push: newList }
} }
Upvotes: 0
Reputation: 21826
State is immutable. You can use immutability-helper for ease of manipulation. But in plain JavaScript, the code is as follows:
let { school } = this.state;
school = Object.assign({}, school);
school.students = school.students.concat(newStudents);
this.setState({ school });
With immutability helper, the code will be a bit less.
let { school } = this.state;
school = update(school, {
students: {
$push: newStudents
}
);
this.setState({ school });
Upvotes: 0