2

So I have an app that looks like this (tried to simplify as much as possible):

// file with context
const SomeContext = React.createContext({});
// file with app root
class App extends Component {
  constructor() {
    super();
    this.state = {
      someValue: 123
    };
  }

  doSomething() {
    // this does not work,
    // as "this" is context value
    this.setState({
      someValue: someValue + 1
    });
  }

  render() {
    // create context values
    const value = {
      someValue: this.state.someValue
      doSomething: this.doSomething
    };
    return <SomeContext.Provider value={value}><ChildComponent/></SomeContext>;
  } 
}
// file with child component
class ChildComponent extends Component {
  render() {
    return <button onClick={this.context.doSomething} />
  }
}
ChildComponent.contextType = SomeContext;

I want context to have doSomething method that updates state of the app (specifically increase someValue by 1).

How to correctly execute doSomething method from child component?

Do I have to do doSomething: this.doSomething.bind(this)? or there is a better way?

edit question is less about how to get "this", but more about what's the recommended way to do it in this case. Maybe I should not add method to context at all?

Marvin3
  • 5,741
  • 8
  • 37
  • 45
  • 1
    bind this or use arrow syntax – xadm May 21 '19 at 10:09
  • 1
    here is the issue : doSomething = () => { // this does not work, // as "this" is context value this.setState({ someValue: someValue + 1 }); } you either need to bind or use arrow function to get this value – Shubham Verma May 21 '19 at 10:10
  • @ShubhamVerma please see edit to the quesiton – Marvin3 May 21 '19 at 10:13
  • 1
    I would like to suggest to go through this article: https://medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1 . If you still have doubt then i will explain – Shubham Verma May 21 '19 at 10:24
  • 1
    Possible duplicate of https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback . – Estus Flask May 21 '19 at 11:01
  • This is the same problem and possible solutions are the same, basically an arrow vs `bind`. No, this is about `this`. `doSomething` is a callback and should be treated as such. When you need to pass it though React context, you need that. – Estus Flask May 21 '19 at 11:02

0 Answers0