Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux componentDidUpdate get previous state

Tags:

reactjs

redux

I refactored Redux into my code, but can't figure out how to get the previous state. I need this state for my componentDidUpdate lifecycle method so that I can call other methods without getting trapped in an infinite loop.

// when component re-renders
componentDidUpdate(prevState) {
 // if the current page changes, or the search term changes.
 if(prevState.currentPage !== this.props.bucketlistState.currentPage || 
  prevState.searchTerm !== this.props.bucketlistState.searchTerm) {
  this.getBucketlists();
 }
}
like image 574
kawerewagaba Avatar asked Jan 31 '18 09:01

kawerewagaba


2 Answers

prevState is the second parameter to componentDidUpdate, The first parameter is prevProps

// when component re-renders
componentDidUpdate(prevProps, prevState) {
 // if the current page changes, or the search term changes.
 if(prevState.currentPage !== this.props.bucketlistState.currentPage || 
  prevState.searchTerm !== this.props.bucketlistState.searchTerm) {
  this.getBucketlists();
 }
}

Check the documentation

Syntax:

componentDidUpdate(prevProps, prevState)

PS: Its an antipattern to have a state that is directly derivable from props. You should instead directly use props and compare them in componentDidUpdate like

// when component re-renders
componentDidUpdate(prevProps, prevState) {
 // if the current page changes, or the search term changes.
 if(prevProps.bucketlistState.currentPage !== this.props.bucketlistState.currentPage || 
  prevProps.bucketlistState.searchTerm !== this.props.bucketlistState.searchTerm) {
  this.getBucketlists();
 }
}

and since you are using props only for comparison, a more suited place before v16.3 of React would be to do it is the componentWillReceiveProps function, however this function is likely to be removed in future major React release and it is expected for you to use componentDidUpdate. For more information please check

Can getDerivedStateFromProps be used as an alternative to componentWillReceiveProps

// when component re-renders
componentWillReceiveProps(nextProps, nextState) {
 // if the current page changes, or the search term changes.
 if(nextProps.bucketlistState.currentPage !== this.props.bucketlistState.currentPage || 
  nextProps.bucketlistState.searchTerm !== this.props.bucketlistState.searchTerm) {
  this.getBucketlists(nextProps);
 }
}
like image 157
Shubham Khatri Avatar answered Sep 18 '22 15:09

Shubham Khatri


componentDidUpdate takes two parameters the first the previous props and the second the previous state

componentDidUpdate(prevProps , prevState) {
like image 44
Ali Faris Avatar answered Sep 18 '22 15:09

Ali Faris