Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

252
Visualizações
TypeError: this.state.toLocaleTimeString is not a function in React

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda