NightFury
NightFury

Reputation: 13546

Attempted to assign to readonly property ECMAScript React Native

I am trying to assign a value to an array declared in my Component. Unfortunately, exception is thrown.

TypeError: Attempted to assign to readonly property

Even if I remove strict mode, still exception is being raised. Can please someone guide me how can I make a variable both readable and writable? Thanks..!

Code:

class RootView extends Component {

  cachedData : []; //declared array here


//trying to assign dictionary in some function

someFunction(results) {

    this.cachedData[this.state.searchString.length - 1] = results;
    //exception raised here
}

}

Upvotes: 2

Views: 9646

Answers (1)

Ben Fortune
Ben Fortune

Reputation: 32127

Your syntax is incorrect. Add it to a constructor.

class RootView extends Component {

  constructor() {
    super();
    this.cachedData = [];
  }
  someFunction(results) {
    this.cachedData[this.state.searchString.length - 1] = results;
  }
}

If your transpiler supports experimental code (stage 0), you can use the following:

class RootView extends Component {
  cachedData = [];
  someFunction(results) {
    this.cachedData[this.state.searchString.length - 1] = results;
  }
}

Upvotes: 5

Related Questions