Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react component state change after ajax call but does not rerender component

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.

like image 758
sinawic Avatar asked Aug 25 '18 15:08

sinawic


1 Answers

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

like image 123
Hemadri Dasari Avatar answered Sep 19 '22 10:09

Hemadri Dasari