Bhavya Arora Bhavya Arora - 1 year ago 89
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.

this.setState({ itemInd.expState : 0 });

It gives me
Unexpected token

I have

this.state = {
itemList: [],

each element in itemList has :
title, desc, expState

Answer Source

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 = => {
  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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download