Search code examples
javascriptreactjssetstate

How to log both prevState and original state in React?


I have a toggle switch that goes from true to false.

flipSwitch = () => {
    console.log(this.state)
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }))
  }

Everything is working like it is supposed to, but I want to log both the prevState and original state at the same time. I tried below adding a callback function after setting the prevState, but then it breaks my toggle switch.

flipSwitch = () => {
    console.log(this.state)
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }, () => console.log(prevState)))
  }

Solution

  • Thats not correct what you're trying to do at here

    flipSwitch = () => {
        console.log(this.state)
        this.setState(prevState => ({
          isToggleOn: !prevState.isToggleOn
        }, () => console.log(prevState)))
      }
    

    You won't have access to prevState in 2nd parameter of setState.

    You should modify your setState function like this

    flipSwitch = () => {
        console.log(this.state) // this refers to previous state here
        this.setState(prevState => {
          console.log(prevState) // prevState refers to previous state
          return ({
            isToggleOn: !prevState.isToggleOn
          })
        }, () => console.log(this.state) // here this refers to updated state)
      }
    

    E.g you can try

    import React from "react";
    
    class App extends React.Component {
      constructor() {
        super();
        this.state = {
          isToggleOn: false
        };
      }
      flipSwitch = () => {
        console.log(this.state);
        this.setState(
          prevState => {
            console.log("prevState", prevState);
            return {
              isToggleOn: !prevState.isToggleOn
            };
          },
          () => {
            console.log("setState Callback", this.state);
          }
        );
      };
    
      render() {
        return (
          <div className="App">
            <button onClick={this.flipSwitch}>
              {this.state.isToggleOn ? "Flipped" : "Flip Switch!"}
            </button>
          </div>
        );
      }
    }
    
    export default App;