0

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",
            }
        ]
    }
}

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@HareeshSNair, Can you tell me in which line you get syntax error
I have updated the answer, can you please check whether it is working
0

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 });

Comments

0

Check out immutability helper. https://github.com/kolodny/immutability-helper/

import update from ‘immutability-helper’;
...
const newState = update( this.state, {
    school: {
        [key]: { $push: newList }
    } }

2 Comments

You gotta import update from immutability helper lib. Check out the docs I have sent
@HareeshSNair I have updated my answer to include an import statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.