'Cannot get prevState from componentDidUpdate lifecycle hook in React.js v18.1.0
import React, { Component } from "react";
class Counter extends Component {
constructor(props) {
super(props);
this.state = { counter: 1 };
}
handleIncrement = () => {
this.setState({ counter: this.state.counter + 1 });
};
componentDidUpdate(prevState) {
console.log("prevState", prevState);
}
render() {
return (
<React.Fragment>
<p>{this.state.counter}</p>
<button onClick={this.handleIncrement}>Increment</button>
</React.Fragment>
);
}
}
export default Counter;
I want to access the prevState prop returned from the componentDidMount lifecycle method. However, I get an empty object when I console.log(prevState). Please find attached image of the same. I want the object of the previous state in the console.
Please help me out whether I'm doing something syntactically wrong or it something unexpectedly breaking in the never version of React. I'd love to hear from you.
Thanks!
Solution 1:[1]
You have to specify both inputs (prevProps, prevState)
componentDidUpdate(prevProps, prevState) {
console.log("prevState", prevState.counter);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bas bas |

