Anders Kitson
Anders Kitson

Reputation: 1545

Trying to setup a countdown clock to a specific date with countdown,js in react

I have this nearly working, however my setInterval function wont setState inside of componenent willMount, I can't seem to figure out why this.setstate is returning a error is not a function. Here is my code so far, any help would be greatly appreciated.

import React from "react"
import { Link } from "gatsby"

import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
import countdown from "countdown"

class Timer extends React.Component{
  constructor(props){
    super(props)
    let time = countdown( new Date(2021, 4, 28) );
    this.state = {
      timeLeft: time.toString()
    }

  }


  componentWillMount(){
    const countyCount = setInterval(function(){
      let timeLeft = countdown( new Date(2020, 4, 28) );
      this.setState(timeLeft.toString())
    }, 1000)

  }

  render() {
    const {timeLeft} = this.state
    return <span>{timeLeft}</span>
  }
}

const IndexPage = () => {


  return(
    <Layout>
      <SEO title="Home" />
      <Timer/>
      <p>Welcome to your new Gatsby site.</p>
      <p>Now go build something great.</p>
      <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
        <Image />
      </div>
      <Link to="/page-2/">Go to page 2</Link>
    </Layout>
  )
}


export default IndexPage

Upvotes: 0

Views: 240

Answers (1)

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

You are using function which changes the scope, and not setting a key for this.setState. Correct way would be:

const countyCount = setInterval(() => {
  let timeLeft = countdown( new Date(2020, 4, 28) );
  this.setState({timeLeft: timeLeft.toString() })
}, 1000)

Upvotes: 2

Related Questions