Reputation: 1203
In my React application, I am using a callback to perform a delete action against an API using the axios library:
deleteBook(selectedBook) {
return this.setState({selectedBook:selectedBook})
axios.delete(this.apiBooks + '/' + this.selectedBook.id)
.then((res) => {
console.log(res)
})
}
I get an error message in the console: "Unreachable code". I think my syntax it's wrong. I would like to perform 2 actions:
1) Setting the state of selectedBook.
2) Deleting the book item using the Axios library delete method.
Upvotes: 1
Views: 7066
Reputation: 2589
You dont need a return
there. Because your function contains promise (axios) You can place a callback if you want to know when axios request is finished.
deleteBook(selectedBook) {
const self = this
axios.delete(this.apiBooks + '/' + this.selectedBook.id).then((res) => {
console.log(res)
// we can update the state after response...
self.setState({selectedBook:selectedBook})
})
}
Upvotes: 1
Reputation: 1544
Get rid of the return. You don't want to return from your function at that point. You only want this.setState(...) there. That would be why you get 'unreachable code', because nothing under the return will execute.
Also, I would do the setState() after axios returns successfully. You probably don't want to do it if axios fails, since your local state will not reflect what is going on if the delete fails. setState() also causes a re-render of your component, so it's better to do it after your API call has completed.
Upvotes: 2