Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React state values disappearing

Tags:

reactjs

In React i have a button that changes state object property value called one. For some reason after i click button, other state values(state object propery value two and three) will disappear. When i console.log it says undefined. Any help?

import React, { Component } from 'react';
import './App.css';



class App extends Component {

  constructor(props){
    super(props);

    this.state = {

      numbers:{
        one:1,
        two:2,
        three:3
      },

    };

  }


  decrement = () => {
    this.setState(prevState => {
      return {
        numbers:{
          one: prevState.numbers.one - 1
        }

      }
    }, () => console.log(
            this.state.numbers.one,
            this.state.numbers.two,
            this.state.numbers.three
      ));

  }

  render() {



    return (
      <div className="App">
         <div>{this.state.numbers.one}</div> 
         <div>{this.state.numbers.two}</div> 
         <div>{this.state.numbers.three}</div>


          <br/>
          <button onClick={this.decrement}>ok</button>     
      </div>
    );
  }
}

export default App;
like image 714
Pleinair Avatar asked May 09 '26 22:05

Pleinair


1 Answers

you are replacing the numbers object when setting the state and you should clone it instead

this.setState(prevState => {
      return {
        numbers:{
          ...prevState.number,
          one: prevState.numbers.one - 1
        }

      }
    }, () => console.log(
            this.state.numbers.one,
            this.state.numbers.two,
            this.state.numbers.three
      ));
like image 136
AngelSalazar Avatar answered May 20 '26 01:05

AngelSalazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!