0

In the following example why the state is not getting updated? Can someone help me out ?

Code Snippet:

import React, { Component } from 'react';

class HomeClass extends Component {

  state = {
    name: "Jack Rogers",
    age: 25,
    city: "New York"
  }

  alpha(){
    this.setState({name: "Julious Cezer", age: 59, city: "Rome"})
  }

  render() {
    return (
      <div>
        <p>{this.state.name + "/" +  this.state.age + "/" +  this.state.city }</p>
        <button onClick={this.alpha}>Change Values</button>
      </div>
    )
  }
}

export default HomeClass;

Error:

enter image description here

Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • 1
    Use `alpha = () => {` instead of `alpha() {` in order to bind the method to the instance. This is definitely a duplicate somewhere... – Patrick Roberts Mar 20 '20 at 12:25
  • Or https://stackoverflow.com/q/31045716/3001761 maybe, but there are loads if you search for your error message – jonrsharpe Mar 20 '20 at 12:28
  • you want state inside the `constructor` like `constructor(props) { super(props); this.state = { State here}; }` – Abdullah Abid Mar 20 '20 at 12:29
  • @jonrsharpe that one doesn't use class syntax so it's a little less applicable here. But yes I agree there are likely multiple others. – Patrick Roberts Mar 20 '20 at 12:29
  • @AbdullahAbid you're wrong, the way that state is initialized in the question works fine. Try it. That property initialization syntax is functionally equivalent to the constructor in your comment. – Patrick Roberts Mar 20 '20 at 12:30

0 Answers0