1

How can I achieve this using the spread operator/ES6?

I want to loop through my data and populate my state with an array of objects where the objects contain two key/value pairs. I would like it to be like...

this.state = {
data: [ {indexNumber: 1, show: false}, {indexNumber: 2, show: false}, {indexNumber: 3, show: false} ]

My [mutated] version;

this.state = { data: []}

data.map((element, index) => {
    this.state.data.push({ indexNumber: index, show: false}] })
});

1 Answer 1

1

You cannot modify the state object. You will have to call setState and use a new value:

this.setState({data: [...this.state.data, {indexNumber: index, show: false}]})

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

Comments

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.