'Undefined 'this' when handing class method to React component
I have API methods for my React app within an API class:
class API {
constructor() {
//setup axios
}
async deleteEquipment(item) {
return this.axios.delete(...paths and stuff..)
}
}
export default API(config)
This works fine for most of my code, except when I need to hand it to components through the props, like so:
import API from '../path/to/api.js'
.. code
<PageTable
deleteItem={API.deleteEquipment}
...more props
/>
This doesn't work as it seems this used in the class to reference axios is now undefined.
this.axios leads to Cannot read properties of undefined (reading 'axios')
I have tried late binding, to bind the method to the class like so:
<PageTable
...more props
deleteItem={API.deleteEquipment.bind(API)}
/>
but it doesn't seem to have much effect. Any ideas how to keep the this reference to the class when the method is called by PageTable ?
Thanks in advance!
Solution 1:[1]
try to bind deleteEquipment in constructor
this.deleteEquipment = this.deleteEquipment(this);
also use await with async functions
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ramy Ragab |
