0

Im trying to add more than one item into this array but I'm not sure how to do so, any feedback is appreciated!

async componentDidMount() {

for (i = 0; i < this.state.permissionsResponseData.length; i++) {
                if (this.state.permissionsResponseData[i].role_id === this.state.roleResponseDataID.id) {
                    await this.setState({
                        accessRoleData: this.state.permissionsResponseData[i].data
                    })
                }
            }
}
2
  • About what array are u talking? Commented Jul 15, 2020 at 16:23
  • @VaganM. accessRoleData this is how im initializing it state = { accessRoleData: []} Commented Jul 15, 2020 at 16:25

2 Answers 2

1

There is a few changes you need to do here.

First change, setState is not an async function, so you should remove the await

 await this.setState({

I'm correct to assume the accessRoleData is an array?

If it's and you want to add items there, you can use the prevState from setState method, ,like:

 this.setState((prevState) => ({
      accessRoleData: [...prevState.accessRoleData, this.state.permissionsResponseData[i].data]
}));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your feedback! Yeh accessRoleData is an array, after adding your changes I get the following warning Function declared in a loop contains unsafe references to variable(s) 'i'
Just change ‘for(i=‘ by ‘for(let i=‘
0
this.setState((prevState, props) => ({
   accessRoleData: [...prevState.accessRoleData, 
             this.state.permissionsResponseData[i].data]
}))

1 Comment

some comments with the code would help understand better.

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.