Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setInterval in React with Typescript

I'm trying to render a dynamic progress bar in react/typescript. I was able to do this in react but converting this into typescript gives me;

[ts] Property 'setInterval' does not exist on type 'Jockey'. any

with a warning underline on setInterval call inside componentDidMount.

With react only I used this.interval = setInterval(this.timer, this.state.interval); inside componentDidMountand it worked but with typescript's strict typing I'm not sure how to do this.

Jockey.tsx

import * as React from 'react';

interface Props {
    color: string;
    avatar: string;
}

interface State {
    interval: number;
    progress: number;
}

export class Jockey extends React.Component<Props, State> {

    constructor(props: Props) {
        super(props);
        this.state = {
          interval: Math.floor(Math.random() * 500),
          progress: 0,
        };
    }

    componentDidMount () {
        this.setInterval(this.timer, this.state.interval);
    }

    timer () {
        this.setState({ progress: this.state.progress + 1 });
        console.log('anyhting');
        
        (this.state.progress >= 99) ? this.setState({ progress: 100 }) : this.setState({ progress: 0 }) ;
    }

    render() {
        return (
            <div>
                <div className="App-lane">
                    {/* <img src={ this.props.avatar } alt=""/> */}
                    <progress value={this.state.progress} color={this.props.color} max="100" />
                </div>
            </div>
        );
    }
}
like image 697
colin_dev256 Avatar asked Jul 17 '26 08:07

colin_dev256


1 Answers

this.setInterval() doesn't exist.

I assume you're trying to create an interval and save a reference so that you can clear it later.

See below for a rough example of how one might achieve this.

Set Interval

componentDidMount () {
  this.interval = setInterval(this.timer, this.state.interval)
}

Clear Interval

componentWillUnmount() {
  clearInterval(this.interval)
}

Further Reading

See the setInterval() references in React Docs: State and Lifecycle for more info.

All the best ✌️

like image 171
Arman Charan Avatar answered Jul 18 '26 22:07

Arman Charan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!