0

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);

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking in angular way :)
1

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
    );
}
}

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.