Home > database >  TypeError: this.state.toLocaleTimeString is not a function in React
TypeError: this.state.toLocaleTimeString is not a function in React

Time:10-04

This is code displaying what time is.

I set state to new Date() and give setState() new Date() as a parameter.

class Clock extends Component {
  constructor(props) {
    super(props)
    this.state = new Date()

  }

  componentDidMount() {
    this.timerID = setInterval(()=> this.tick(), 1000)
  }

  componentWillUnmount() {
    clearInterval(this.timerID)
  }

  tick() {
    this.setState(new Date())
  }

  render() {
    return (
      <div>
        <h2>It is {this.state.toLocaleTimeString()}.</h2>
      </div>
    )
    
  }
}

ReactDOM.render(<Clock />, document.getElementById('root'));

Running code, getting error like below

TypeError: this.state.toLocaleTimeString is not a function

Clock.render
  29 | return (
  30 |   <div>
  31 |     <h1>Hello, world!</h1>
> 32 |     <h2>It is {this.state.toLocaleTimeString()}.</h2>
     | ^  33 |   </div>
  34 | )
  35 | 

I can't understand what problem is.

How could I fix it?

CodePudding user response:

You're not using any key to store/update the state, which is causing this error, since React doesn't find anything to update. I've used the key date to store and update the state on every second.

so, the state will be

this.state = {
  date: new Date()
};

and the tick function update.

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

and also the rendering part to use the state key.

<h2>It is {this.state.date.toLocaleTimeString()}.</h2>

Your updated code should be something like below.

import { render } from "react-dom";
import React from "react";

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

  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

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

  render() {
    console.log(this.state);
    return (
      <div>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
render(<Clock />, rootElement);

React docs has some useful information regarding the state management and other related topics, which you should definitely take a look at, to understand how state works and re-renders UI accordingly.

CodePudding user response:

Try using this.state = {date: new Date()}; in your state declarations instead.

  • Related