Axel Kennedal
Axel Kennedal

Reputation: 555

Using a prop to start a timer in React Native

I've got a <Timer/> component which is able to transition between a couple of different states (EDITING, READY and TICKING), and the UI for all of these states contain a <CountDown/> component I've created. The <CountDown/> component takes a boolean prop edit which determines if it takes user input or just displays a countdown.

The issue I'm having is with changing whether the <CountDown/> is counting down or just displaying static numbers. My idea was to make the <CountDown/> component also take a boolean prop ticking which would activate/deactivate the countdown, but currently it seems like my implementation starts a new timer (i.e. calls setInterval()) every time the <CountDown/>component is re-rendered (every second).

So the big question is how should I design my <CountDown/> component to have it start counting down as I want it to?

(It would be especially appreciated if the solution used the new React lifecycle methods instead of the UNSAFE ones.)

The render function for my <Timer/> looks like this (details omitted for brevity):

render () {
        let countDown;

        if (this.state.currentState == TimerStates.TICKING) {
            countDown = (
                    <Countdown
                        countdownFromSeconds={this.state.countDownFrom}
                        ticking={true}
                        updateProgress={this.handleProgressUpdate}
                    />
            );
        } else if (this.state.currentState == TimerStates.EDITING) {
            countDown = (
                <Countdown
                    edit={true}
                    ticking={false}
                    onEdit={this.handleSelectedTimeUpdate}
                />
            );
        } else if (this.state.currentState == TimerStates.READY) {
            countDown = (
                <Countdown
                    edit={false}
                    ticking={false}
                    countdownFromSeconds={this.state.countDownFrom}
                />
            );
        }

        return (
            <View style={styles.container}>
                {countDown}
            </View>
        );
    }

The <CountDown/> component looks like this (unrelated details omitted):

export default class Countdown extends Component {
    static propTypes = {
        countdownFromSeconds: Proptypes.number,
        edit: Proptypes.bool,
        ticking: Proptypes.bool,
    };

    constructor(props) {
        super(props);
        if (this.props.edit == true) {
            this.state = {
                totalTimeInSeconds: 0,
                ticking: false,
                seconds: 0,
                minutes: 0,
                hours: 0
            };
        } else if (this.props.ticking == true) {
            const startingTime = this.secondsToTimeComponents(props.countdownFromSeconds);
            console.log("Constructor for ticking");
            this.state = {
                totalTimeInSeconds: props.countdownFromSeconds,
                ticking: true,
                seconds: startingTime.seconds,
                minutes: startingTime.minutes,
                hours: startingTime.hours
            };
            if (this.props.ticking == true) {
                this.timerStart();
            }
        }
    }

    UNSAFE_componentWillReceiveProps(nextProps) {
        console.log("Got new prop: " + nextProps.ticking + " currently ticking: " + this.state.ticking);
        if (nextProps.ticking == true && this.state.ticking == false) {
            this.timerStart();
            return {
                ticking: true
            };
        } else return null;
    }

    componentWillUnmount() {
        this.timerStop();
    }

    timerStart = () => {
        console.log("Started timer");
        const interval = setInterval(this.tick, 1000);
        this.setState({
            interval,
        });
    }

    timerStop = () => {
        clearInterval(this.state.interval);
    }

    timerDone = () => {
        console.log("Timer done!");
    }

    tick = () => {
        if (this.state.totalTimeInSeconds == 0) {
            this.timerStop();
            this.timerDone();
        } else {
            this.setState({
                totalTimeInSeconds: this.state.totalTimeInSeconds - 1
            });
        }
        this.setState(this.secondsToTimeComponents(this.state.totalTimeInSeconds));
    }

    render() {
        return (
            <View style={styles.container}>
                <TimeUnitDisplay unit="hours" value={this.state.hours} edit={this.props.edit} onChange={this.handleHoursChanged} />
                <Text style={styles.separator}>:</Text>
                <TimeUnitDisplay unit="minutes" value={this.state.minutes} edit={this.props.edit} onChange={this.handleMinutesChanged} />
                <Text style={styles.separator}>:</Text>
                <TimeUnitDisplay unit="seconds" value={this.state.seconds} edit={this.props.edit} onChange={this.handleSecondsChanged} />
            </View>
        );
    }
}

This is the debug output I'm getting:

04-29 14:06:32.764 19850 20081 I ReactNativeJS: Started timer
04-29 14:06:33.789 19850 20081 I ReactNativeJS: Timer done!
04-29 14:06:33.859 19850 20081 I ReactNativeJS: Started timer
04-29 14:06:34.877 19850 20081 I ReactNativeJS: Timer done!
04-29 14:06:34.957 19850 20081 I ReactNativeJS: Started timer
04-29 14:06:35.967 19850 20081 I ReactNativeJS: Timer done!
04-29 14:06:36.050 19850 20081 I ReactNativeJS: Started timer
04-29 14:06:37.064 19850 20081 I ReactNativeJS: Timer done!
etc...

Upvotes: 0

Views: 748

Answers (1)

Roy Wang
Roy Wang

Reputation: 11270

Your return { ticking: true } in componentWillReceiveProps does nothing as it does not make use of the return value (unlike getDerivedStateFromProps). You need to explicitly call setState({ ticking: true}) instead.

Instead of clearInterval when props.ticking is false, and starting a new interval when it's true, you can consider just keeping the initial setInterval instance alive but avoid updating the timer when props.ticking is false:

tick = () => {
  if (!props.ticking) return;
  // rest of the code
}

However, the behavior will be slightly different as the ticking might be executed as soon as props.ticking changes to true.

Also setInterval should be called in componentDidMount instead of constructor.

Upvotes: 1

Related Questions