0
votes

I can't figure out what's wrong with my code.

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

class Clock extends React.Component 
{
    constructor(props)
    {
        super(props);
        //defining state
        this.state={date:new Date()};
    }

    updateTime()
    {
        //updating the time by set state
        this.setState( (state,props) =>  {date:new Date()}  );
    }

    render()
    {
        return (
            <div>
                <h2>Now the time is {this.state.date.toLocaleTimeString()}</h2>
                <button onClick={this.updateTime}>Update Time</button>
        
            </div>
        );
    }
}
export default Clock;

Getting below error on updating the state i.e. when the button is clicked.

TypeError: Cannot read property 'setState' of undefined updateTime
C:/Users/YV/YVSCodes/React-Van/hi-app/src/setState-event-binding-exampleComponent.js:21
18 | updateTime() 19 | { 20 | //updating the time by set state

21 | this.setState( (state,props) => {date:new Date()} );

2

2 Answers

1
votes

You need to bind updateTime

constructor(props) {
   ...
   this.updateTime = this.updateTime.bind(this)
}

or use arrow function

updateTime = () => {
    //updating the time by set state
    this.setState( (state,props) =>  {date:new Date()}  );
}

and change your setState to

this.setState({
  date: new Date()
});

or

this.setState( (state,props) =>  ({date:new Date()})  );
0
votes

Just replace

updateTime() {
    //updating the time by set state
    this.setState( (state,props) =>  {date:new Date()}  );
}

with this

updateTime = () => {
    this.setState((state, props) => {
        return {
          date: new Date()
        };
    });
};