Reputation: 183
handleDelete(event) {
axios.post('http://localhost:8080/removeActor', {
'name': event.target.value
})
.then((response) => {
this.componentDidMount();
})
event.preventDefault();
}
My componentDidMount just fixes up the page by reading the database like the post on a page had someone deleted a post it would update the page. So I can call this.componentDidMount() on get request and it would work, but whenever I use it on a post request i get "Cannot read property 'componentDidMount' of undefined"
How do I achieve what I want without this error then?
Upvotes: 1
Views: 115
Reputation: 5786
You are doing something basically wrong with respect to react here. Why are you invoking the component event lifecycle manually?
The way to change the component's behaviour aka states is via setState
or useState
hooks or other state management libraries that follow flux architecture like Redux etc.,
Though you get this error coz this
is not bounded using bind
, you should not use this way. I would highly recommend to go through basic react concepts.
Upvotes: 1
Reputation: 68
Edit: Karthik is right, you have to bind this to the handleDelete function.
The this
keyword changes from context to context and it's a bit tricky to know what exactly it points to, and when. In this case, the error actually means this
is undefined, probably because it is being referenced inside of a promise. Normally what you would do is create a reference to this
someplace where it refers to what we intend it to (in this case your component):
handleDelete(event) {
const self = this;
axios.post('http://localhost:8080/removeActor', {
'name': event.target.value
})
.then((response) => {
self.componentDidMount();
})
event.preventDefault();
}
You might also consider moving your code in componentDidMount
into a new function since componentDidMount
is part of the React component lifecycle and it's not a good idea to call it explicitly unless you really know what you're doing.
Upvotes: 0