2

I am using picker-module in React native. I have to create a dataset for this. It is okay to write Dataset with my hand, but when I print it with for for a list, I get the following error. What is the solution?

//working
const dataset = [
    {
        value: "1",
        label: "1",
    },
    {
        value: "2",
        label: "2",
    },
    {
        value: "3",
        label: "3",
    }
]

//not working
for (let i = 0; i < 3; i++) {
    this.setState({yearList:this.state.yearList.push({value:`${i}`,label:`${i}`})})
}

error

1 Answer 1

1

The React docs says:

Treat this.state as if it were immutable.

Your push will mutate the state directly and that could potentially lead to error prone code, even if you are "resetting" the state again afterwards. as an example, it could lead to that some lifecycle methods like componentDidUpdate won’t trigger.

The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:

this.setState({
  arrayvar: [...this.state.arrayvar, newelement]
})
Sign up to request clarification or add additional context in comments.

1 Comment

gardash means 'bro' in Turkish :D

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.