1

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;
1

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, providing your target supports them, you could use an arrow function which has the same effect but is more idiomatic/concise in modern javascript. Considering it looks like you're using babel, this is the right way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.