rashidnk
rashidnk

Reputation: 4292

React.js Value not updated on button

Console.log printing the incremented value, but value not updated in button

'use strict';

const e = React.createElement;

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { val: 0 };
  }

  render() {
    return e(
      'button',
      {
        onClick: () => {
          this.state.val = this.state.val + 1
          console.log(this.state.val)
        }
      },
      'Like' + this.state.val // here Like 1 should be displayed
    );
  }
}

const domContainer = document.querySelector('#root');
ReactDOM.render(e(Counter), domContainer);

Upvotes: 0

Views: 96

Answers (3)

Mir
Mir

Reputation: 114

You have to update React state via this.setState() function. Otherwise, the component does not re-render. That's basic of React. You should read more React documents or do some tutorials.

You can read more here!

Upvotes: 1

rockingskier
rockingskier

Reputation: 9346

You should never update state directly. Always use setState

this.state.val = this.state.val + 1;  // bad
this.setState((state) => ({           // good
    val: state.val + 1
}))

Otherwise React will not "see" the update and will not re-render.

Upvotes: 3

Amruth
Amruth

Reputation: 5912

You have to use setState to update the state. and state update is asynchronous call so you have to use call back functions to check weather store is updated or not.

class Counter extends React.Component {
constructor(props) {
    super(props);
    this.state = { val: 0 };
    this.updateState = this.updateState.bind(this);
}

updateState(){
        this.setState({val : this.state.val + 1 }, function(){
            console.log(this.state.val)
        })
}

render() {
    return e(
    'button',
    {
        onClick: () => {this.updateState()
        }
    },
    'Like' + this.state.val
    );
}
}

Upvotes: 1

Related Questions