Joe
Joe

Reputation: 25

React Native Countdown Timer keeps resetting

I have a countdown timer set at every 20 seconds an alert prompt is shown and a choice to extend timer or cancel. Every time i would go to another screen on my app and come back to the home page, the timer keeps resetting itself and will have multiple timers in the background and then multiple prompts. This even includes when extending timer as well.

How can i stop it from resetting the timer each time i go through another screen on the app and keep it to one timer?

Please see my example code:

import CountDown from 'react-native-countdown-component';

export default class App extends React.Component {



constructor(props) {
    super(props);

    this.state = {
      timer: 20,
    };
  }
};
timesUp = () => {
    Alert.alert(
      "ALERT ",
      'Would you like to extend timer?',
      [
        {
          text: 'Extend Timer',
          onPress: () =>
            this.setState(previousState => ({
              timerId: ++previousState.timerId,
            })),
        },

        {
          text: 'Cancel',
          onPress: () => console.log('Cancel Pressed'),
        },
      ],
      { cancelable: false }
    );
  };

render(){
 return(
        <View style={styles.countdownContainer}>
          <CountDown
            id={this.state.timerId}
            until={this.state.timer}
            onFinish={this.timesUp}
            timeToShow={['M', 'S']}
            digitStyle={{ backgroundColor: '#FFF' }}
            size={20}
          />
        </View>
 );
}

Upvotes: 1

Views: 1441

Answers (1)

user9408899
user9408899

Reputation: 4540

How can i stop it from resetting the timer each time i go through another screen

It is resetting because the component is unmounted when you change the screen.

You can define your timer in your top level component. Top level component is never unmounted, so your timer will not be canceled when you change screen.

Upvotes: 1

Related Questions