Bhavya Arora Bhavya Arora - 6 months ago 13
Javascript Question

webpack ReactJS: Unexpected token at this.setState

I am trying to change state of all the elements in an array in ReactJS as shown below. This is my First application, so I am not able to know what is wrong in over here.

closeState(){
this.state.itemList.forEach(function(itemInd){
this.setState({ itemInd.expState : 0 });
}
});


It gives me
Unexpected token
error

I have

this.state = {
...........
itemList: [],
.....
}


each element in itemList has :
title, desc, expState
.

Answer

I think you chose wrong way to solve this issue., from your example I understood that you want to set expState to 0, for each element in itemList., if it is true better do it like this

const newItemListState = this.state.itemList.map((itemInd) => {
  return Object.assign(itemInd, { expState: 0 });
});

this.setState({ itemList: newItemListState })

In your example you have several mistakes

  1. You forgot add ) after callback function
  2. You need set this for .forEach callback, or use arrow function

    2.1. this.state.itemList.forEach(function(itemInd) { }, this);

    2.2. this.state.itemList.forEach((itemInd) => { });

  3. You can't use this { itemInd.expState : 0 } expression.

Comments