Ishan Patel
Ishan Patel

Reputation: 6091

What is the best place to update the state in ReactJS?

Currently I am updating my state in componentDidUpdate life cycle function. But then my app is sending continuous GET request because of the nature of that function,so I am not sure which place to update the state so I can avoid that.

Following is my code.

componentDidUpdate(){
    if(this.props.id){
        if(!this.props.loadedPost || (this.state.loadedPost && this.state.loadedPost.ID !== this.props.id)){
            axios.get('https://public-api.wordpress.com/rest/v1.1/sites/xhehehshs.wordpress.com/posts/'+this.props.id)
            .then( response => {
                this.setState({ loadedPost: response.data });
            });
        }  
    }
}

Upvotes: 1

Views: 2328

Answers (2)

theJuls
theJuls

Reputation: 7460

componentDidUpdate is a bad place to be doing an AJAX call and updating the state, since well... It is called every time the component gets updated (so stuff like this.setState({}) will trigger it over and over again).

componentDidMount or componentWillMount are the better places to make that call if you want it to be done right before it mounts or as soon as the component mounts.

Edit: After seeing your comment on another answer regarding that you want this to be done after a click, once the component is already mounted. So here is a proposed solution for that:

getPosts () {
  if(this.props.id){
        if(!this.props.loadedPost || (this.state.loadedPost && 
  this.state.loadedPost.ID !== this.props.id)){
            axios.get('https://public-
  api.wordpress.com/rest/v1.1/sites/ishhaanpatel.wordpress.com/posts/'+this.props.id)
            .then( response => {
                this.setState({ loadedPost: response.data });
            });
        }  
    }
}

 handleClick (target, value) {
    // do your magic
    this.getPosts() 
 }

Upvotes: 1

psgivens
psgivens

Reputation: 66

componentDidMount is the ideal spot for AJAX calls. It only runs once right after the component mounts, so you can avoid the infinite loop you've created by making AJAX calls from there.

Here is a nice article explaining all the React lifecycle hooks and what to use them for: https://engineering.musefind.com/react-lifecycle-methods-how-and-when-to-use-them-2111a1b692b1

Upvotes: 3

Related Questions