-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

1
  • 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? Commented Mar 17, 2019 at 6:55

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
    ...

Comments

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.

Comments

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.