0

I want to change the value of currentIndex every 5s but when it comes to this.setState I receive Uncaught TypeError: this.setState is not a function

Here is my code:

constructor() {
        super()
        this.state = {
            currentIndex: 0,
       }
    }

    componentDidMount() {
        this.changeIndex()
    }

    changeIndex() {
        const { currentIndex } = this.state
        setInterval(function () {
            if (currentIndex < 2) {
                this.setState({ currentIndex: currentIndex + 1 })
            } else {
                this.setState({ currentIndex: 0 })
            }
        }, 5000);
    }
Markus Hayner
  • 2,400
  • 1
  • 17
  • 41

2 Answers2

1

use arrow functions:

changeIndex = () =>{
            const { currentIndex } = this.state
            setInterval( ()=> {
                if (currentIndex < 2) {
                    this.setState({ currentIndex: currentIndex + 1 })
                } else {
                    this.setState({ currentIndex: 0 })
                }
            }, 5000);
        }
Manav Mandal
  • 316
  • 1
  • 5
1

Use arrow function :

 setInterval(() => {
        if (currentIndex < 2) {
            this.setState({ currentIndex: currentIndex + 1 })
        } else {
            this.setState({ currentIndex: 0 })
        }
    }, 5000);
Oleg
  • 2,915
  • 1
  • 4
  • 8