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();
}
}
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);
}
}
componentDidUpdate
takes two parameters the first the previous props and the second the previous state
componentDidUpdate(prevProps , prevState) {
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