Home > database >  Cannot get prevState from componentDidUpdate lifecycle hook in React.js v18.1.0
Cannot get prevState from componentDidUpdate lifecycle hook in React.js v18.1.0

Time:05-08

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.

prevState empty object

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!

CodePudding user response:

You have to specify both inputs (prevProps, prevState)

  componentDidUpdate(prevProps, prevState) {
    console.log("prevState", prevState.counter);
  }
  • Related