On this part the user gets to comment on posts. After it gets checked on server side and the data is recieved, I try to change the this.state.comments
value. and so it's done. But the problem is, it is not changing the comment section on component.
I have read the previous questions about rerendering so please don't mark as duplicate. Below is the code:
$.post("requests.php", {
requestKey: 'newComment',
commenterUser: commenterUser,
commenterEmail: commenterEmail,
theComment: theComment,
pnum: pnum}, function(data, status, xhr){
if(status == 'success'){
if(data == 'commented'){
this.setState({
comments: data
})
}else{
}
}
});
The data
received is all the comments related to the post and the comments section is a place where all the comments are shown.
You can also use arrow function instead of doing manual binding.
this.setState is not working because it has scope issue when you use normal function.
Change it to arrow function. Check below code
$.post("requests.php", {
requestKey: 'newComment',
commenterUser: commenterUser,
commenterEmail: commenterEmail,
theComment: theComment,
pnum: pnum}, (data, status, xhr) => {
if(status == 'success'){
if(data == 'commented'){
this.setState({
comments: data
})
}else{
}
}
});
Edit:
If you want to stay away with scope issues you can use arrow function. When you use arrow function then you no need to bind your function manually in constructor
submitComment = () => {
}
If you use normal function and to play with state or props inside that function, then you need to manually refer current object to a local variable like below
let that = this;
that.setState({
name: “update”
});
Sorry if there are any typo mistakes. I am answering in mobile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With