'Why Is this function producing NaN in the DOM?(React)

So I'm working on this portion of an app where I want the number displayed on the page to increase or decrease depending on the hour of the day. At this point I'm using componentDidMount() to use a setInterval() method that takes in a function ( hourCheck ) and an interval.

However, hourCheck is having issues, specifically it's returning NaN in the DOM instead of an actual number. Seems like the state isn't being changed correctly but I'm exactly sure in what way.

Here's the app.js file I'm working with. I set the interval to 8000ms for the sake of time. This is ultimately a counter app.

import React, { Component, useState } from "react";
import { Wrapper } from "./components/Wrapper";
import Title from "./components/Title";
import Count from "./components/Count";
import "./App.css";

class App extends Component {
  state = {
    CountNum: 0,
    
  };

  

 setCountNum = (val) => {
   this.setState({CountNum: val})
 }

 hourCheck = (val) => {

  



  let hourCount = new Date().getHours()

  
  

  if (hourCount >= 9 && hourCount <= 17) {
    this.setState({ CountNum: val + 1 });
  } else if (hourCount <= 8) {
    this.setState({ CountNum: val - 1});
  } else if (hourCount >= 18) {
    this.setState({ CountNum: val - 1});
  }

  console.log(hourCount)
};

loginSomething = (val) => {
  console.log(this.state.HourNum)
};





  render()
   {
    return (
      <Wrapper setCountNum={this.setCountNum} CountNum={this.state.CountNum}>
        <Title>Click Counter</Title>
        <Title>Count:</Title>
        <Count>{this.state.CountNum}</Count>
      </Wrapper>
    );
  }

  componentDidMount() {

    setInterval(this.hourCheck, 8000);
    
     };
  
}



export default App;


Solution 1:[1]

hourCheck function has val parameter and you are not passing that argument in setInterval in componentDidMount. Bind "this" obj to the hourCheck function in setInterval.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shreevathsa Chatra