Reputation: 359
I am new to react native. I have a countdown timer (currently set to 5 seconds) and when the time is up, I want an alert which gives the user an option to restart the timer. There will be other elements in the screen so I don't necessarily want a "refresh" (for example, if the user inputted some text, I don't want that to go away when the timer is extended).
The alert pops up when the time is up, but I'm not sure how to reset the timer via the alert button.
import React, { Component } from 'react';
import {
StyleSheet,
TouchableOpacity,
Text,
View,
TextInput,
Alert,
} from 'react-native'
import CountDown from 'react-native-countdown-component';
export default class Payment extends Component {
constructor(props) {
super(props);
this.state = {
timer: 5,
};
}
timesUp = () => {
Alert.alert(
"Time's Up!",
"How can we help you?",
[
{
text: "Extend Timer",
// I want to restart the timer here
onPress: this.setState(newTime => ({ timer: 5})) },
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed") },
],
{ cancelable: false }
);
}
render() {
return (
<View>
<View style={{ marginTop: 20}}>
<CountDown
size={15}
until={this.state.timer}
onFinish={this.timesUp}
digitStyle={{backgroundColor: '#FFF', borderWidth: 2, borderColor: '#cccccc'}}
digitTxtStyle={{color: 'black'}}
separatorStyle={{color: 'black'}}
timeToShow={['M', 'S']}
timeLabels={{m: null, s: null}}
showSeparator
/>
</View>
);
}
}
Upvotes: 2
Views: 1113
Reputation: 852
Please use setTimeout(function() {}, Time in Milli seconds). Its a native javascript function used to trigger a function after certain time.
Upvotes: 1
Reputation: 865
react-native-countdown-component
provides an id
props to determine if you want to reset the timer. https://github.com/talalmajali/react-native-countdown-component#props
You can just reset the id
when times out.
onPress: () => this.setState({ timerId: newTimerId })
<CountDown id={this.state.timerId} />
Upvotes: 3