UI Developer
UI Developer

Reputation: 177

Trying to update the state of the counter in react

havent been working with React in quite a while. Just got back into it and was trying to update the state. From my knowledge, I should be able to update the state using the method below. However, its not updating the value of the age. Am I missing something?

import React from 'react';
import logo from './logo.svg';
import './App.css';

class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      age: 0
    }

    this.increaseAge = this.increaseAge.bind(this)
  }

  increaseAge=()=> {
    this.setState({
      age: this.state.age + 1
    })

    console.log("hi")
  }


  render() {
    return(
      <div className="app-content">
        <h1>Hey Ninjas</h1>
        <p>{this.state.age}</p>
        <button onClick={this.icreaseAge}>Increment</button>
      </div>
    );
  }
}

export default App;

Upvotes: 1

Views: 62

Answers (3)

faithfull
faithfull

Reputation: 471

As a sidenote, you shouldn't update your state by accessing the component's state the way you did, but rather this way:

increaseAge = () => {
  this.setState((state) => ({ age: state.age + 1 }));
  // or shorter
  this.setState(({ age }) => ({ age: age + 1 }));
}

The problem with your implementation arises from a fact that React's state updates are asynchronous and can be batched so your age update could finally end up with age being overwritten by some other setState call and then eventually being updated incorrectly.

You may take a look at the documentation.

Upvotes: 1

Nazim
Nazim

Reputation: 41

<button onClick={this.icreaseAge}>Increment</button>

You got a typo in the onClick. otherwise it should be working just fine.

<button onClick={this.increaseAge}>Increment</button>

Upvotes: 1

Jason
Jason

Reputation: 67

You have a typo, You missed the letter (n) from increaseAge

This should work now.

        <button onClick={this.increaseAge}>Increment</button>

Upvotes: 1

Related Questions