0

I have this React code:

componentDidMount(){
    this.getBooks();
}
getBooks(){
    axios.get('http://localhost:8000/api/v1/books')
        .then(res => {
            this.setState({books: res.data});
        })
}
deleteBookHandler(id){
    axios.delete(`http://localhost:8000/api/v1/book/${id}`)
        .then(() => {
            this.getBooks();
        })
}

When I use this.getBooks() inside componentDidMount, everything works fine, but when I use the same function inside deleteBookHandled, which is a function I perform when the delete button on one of my grid items is pressed, React throws this error:

Unhandled Rejection (TypeError): _this3.getBooks is not a function

Maybe I'm not understanding properly the this keyword on JavaScript. Where's the error? How can I call getBooks inside 'then'?

Anonymous
  • 171
  • 11
  • 2
    Where do you call `deleteBookHandler`? – CertainPerformance Nov 15 '20 at 00:06
  • For the component's methods you need to use arrow functions or bind them in the constructor. It works in `componentDidMount` because that's a predefined method and React handles that for you – Jayce444 Nov 15 '20 at 00:08
  • [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484) | [How does the “this” keyword work?](https://stackoverflow.com/q/3127429) – VLAZ Nov 15 '20 at 00:08
  • 1
    `delete={this.deleteBookHandler}` looses your context because you pass a function reference only. Make it `delete={() => this.deleteBookHandler}` (I hope I got the JSX context right) – VLAZ Nov 15 '20 at 00:09
  • On my map function i use `delete={this.deleteBookHandler}` and inside component i use `onClick={() => props.delete(props.book.id)}` – Guilherme do Valle Nov 15 '20 at 01:22
  • I resolved using `onClick={props.delete}` and `delete= {() => this.deleteBookHandler(currentBook.id)}` – Guilherme do Valle Nov 15 '20 at 01:34

0 Answers0