0

I have a component with the following functions:

constructor(MyProps: Readonly<MyProps>){
    super(MyProps);
    this.state = {suppliers: [], supplierId:0, supplierName:''};
    this.addSupplier.bind(this);
  }

addSupplier(){
    const {supplierId} = this.state;
    alert('supplierId = ' + supplierId);
}

<Button onClick={this.addSupplier}>Add</Button>

State is initialized as expected b/c this.state.supplierId is bound and displayed as expected in an html input in the component on load. The onChange handler within the html input also calls setState to update state.supplierId as expected. However, when the addSupplier() button gets triggered, the following error occurs:

TypeError: Cannot read property 'supplierId' of undefined

So for some reason, state is not available in this context. Any idea why this is?

user12617173
  • 127
  • 2
  • 10
  • 1
    Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – jonrsharpe Jan 02 '20 at 16:53

2 Answers2

0

Please use the arrow function to create the method

addSupplier = () => {}

or use the below syntax in the constructor

this.addSupplier = this.addSupplier.bind(this);
Nikhil Goyal
  • 1,945
  • 1
  • 9
  • 17
0

To expand on what Nikhil Goyal posted, the reason you're getting an error is because the context of this where the function is being invoked. Non-arrow functions implicitly bind their context when invoked rather then when they're declared. So, when you press the onClick on the Button component, it's searching for this.state.supplierId on the Button context.

ehutchllew
  • 940
  • 8
  • 14