Tanmoy Sarker
Tanmoy Sarker

Reputation: 1266

Calling a function in setInterval gives error in react native

I am working on a React Native app where I'm trying to call a function in setInterval to re-render component in every three seconds. But when I put the function in setInterval it returns the error this.refreshData() is not a function. Here's the code for this I'm having:

 refreshData = async()=> {
  await fetch('https://myapi', {
      method: 'GET',
    })
      .then((response) => response.json())
      .then((response) => {
        this.setState({ tableData1: response.First })
        this.setState({ tableData2: response.Special })
        this.setState({ tableData3: response.Consolidation })
      })
  }
  
    componentWillMount() {
    const { navigation } = this.props;
    this.focusListener = navigation.addListener("didFocus", () => {
      var today = new Date()
      var time = today.getHours()
      console.log(today.getMinutes())
      var weekDay = today.getDay()
      if ((time >= 22) && (time <= 23 )){
       if(today.getMinutes()<=30){
    
      setInterval(function() {
        this.refreshData()
        }, 3000);
    }
    });
  }

How this error can be resolved?

Upvotes: 0

Views: 1076

Answers (2)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7749

Use arrow function.

Try this example:

function refreshData(){
    console.log("called");
}
setInterval(() => {
    this.refreshData();
}, 3000);

Upvotes: 2

Shubham Verma
Shubham Verma

Reputation: 5054

Either bind the setTimeout/setInterval function or use Arrow function i.e

setTimeout(function() { //or setInterval(whatever you need to use)
        this.refreshData()
        }, 3000);
    }
 }).bind(this);

or

setTimeout(() => { //or setInterval(whatever you need to use)
    this.refreshData();
}, 3000);

Upvotes: 1

Related Questions