0

I am trying to display user notes on submit. On componentDidMount I am sending a GET request to the server to initially display data. When a user submits a new comment, on componentDidUpdate I'm checking prevState. If there is any difference found it should load new data from the server.

But inside componentDidUpdate continuous request is sending to the server.

What I have done so far

componentDidUpdate(prevProps, prevState){
    if(prevState.status !== this.props.userDisplayNotes.status){

            // This is GET request to display the data from the server

            this.props.displayUserNotes(this.props.user_id)

    }
}


// Here I'm displaying data on initial rendering with GET request

componentDidMount(){
    this.props.displayUserNotes(this.props.user_id)
}

// This is form submit handler

handleSubmit = (e) => {      
    e.preventDefault();
    this.props.saveUserNote(this.props.user_id, this.state.userNote)

}

Upon successful submission of comment I'm getting a response from server like {"status":"success"}

For state management I'm using Redux.

But inside componentDidUpdate it is sending continuous request to server causing application crashed. Can someone please explain me what I'm doing wrong here?

Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
ConAra
  • 271
  • 5
  • 18
  • would be good if you `console.log` both `prevState.status` and `this.props.userDisplayNotes.status` prior to checking if they're equal – albert Dec 03 '19 at 04:15
  • on console.log prevState.status is showing undefined and this.props.userDisplayNotes.status is showing success – ConAra Dec 03 '19 at 04:19
  • they're not equal so its being called repeatedly – albert Dec 03 '19 at 04:27
  • 1
    Where is `this.state.status` being set? Do you mean to check `prevProps`? As in `if(prevProps.userDisplayNotes.status !== this.props.userDisplayNotes.status)`. – sallf Dec 03 '19 at 04:27
  • @Sallf Thank you so much. I was wrong in comparison. I followed your method and its working fine. – ConAra Dec 03 '19 at 04:35

1 Answers1

0

You can compare previous Props with new one it will fix your problem

componentDidUpdate(prevProps, prevState){
if(prevProps.userDisplayNotes.status !== this.props.userDisplayNotes.status){
        this.props.displayUserNotes(this.props.user_id)
  }
}
Shayan Moghadam
  • 1,860
  • 2
  • 10
  • 19