-1

My JavaScript object has a state declared like this:

state = {isFiltered: false}

I have a method changeState() that basically does the following:

this.setState({isFiltered: true});

However, this will give me an error that says that "setState" is not a function. How can I alter this flag from within a method?

Edit: I wasn't understanding how to bind properly. I'll accept a solution as soon as SOF lets me

  • Can you please add the full code snippet? Before that I have a question why do you want a separate method to changeState when react gives you setState? – Rahul Raut Mar 17 '19 at 06:55

3 Answers3

2

It seems you have no bounding context for this:

A quick fix is to bind this inside the constructor.

this.changeState = this.changeState.bind(this)

If you want to deep dive, you can follow my another post.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
1

Did you bind your changeState function with this?

constructor(props) {
    super(props);
    this.state = {isFiltered: true};

    // This binding is necessary to make `this` work in the callback
    this.changeState = this.changeState.bind(this);
    ...
ttulka
  • 10,309
  • 7
  • 41
  • 52
0

The error is due to different context.

Context is concept which relates 'this' to be associated with specific scope.

For solving the above issue you need to bind your changeState() function using bind().

This will allow changeState to use the context of class where you can access the setState method.

Raj Saraogi
  • 1,780
  • 1
  • 13
  • 21