Britt Shroyer
Britt Shroyer

Reputation: 83

Infinite loop through array of strings in React

New to programming, and I'd really appreciate some help in rendering a React component. I have an array of strings, and I'd like to display each string in that array every 5 seconds on an infinite loop. The error I'm running into when trying to set the state is 'this.setState is not a function'. I'm inclined to think I'm using the wrong lifecycle method or there is a binding issue, but I'm lost. Below is the code. I'd really appreciate some help.

import React, {Component} from 'react';

class Home extends Component{
  constructor(props){
    super(props);
    this.state = {
      service: ''
    }
  }
  componentDidMount(){
    var services = ['Delivering professional and personalized care to your loved ones','Home visits with a personalized health plan', 'Transition Assistace', 'Advocacy and Guidance', 'Respite Care']
    let i=0;
    setInterval(function(){
      console.log('set interval working');
      const currentService = services[i];
      this.setState({
        service: currentService
      })
      i++;
      if(i>=services.length){
        i = 0;
      }
    }, 5000);
  }
  render(){
    console.log('this', this.state.service);
    return(
      <div className="home">
        <div className="profile-img"></div>
        <div className="mission">
          <div className="overlay">
            <p>{this.state.service}</p>
          </div>
        </div>
      </div>
    )
  }
}
export default Home;

Upvotes: 1

Views: 1082

Answers (1)

paqash
paqash

Reputation: 2314

The this in your function in the setInterval isn't the this from ComponentWillMount .. that's why it fails. Do something like:

var that = this;

before you call setInterval and then

that.setState()

You can read more about the this keyword here.

Upvotes: 4

Related Questions