What I want is to display a Image if user does not interact with the app for 1 minute. I have tried implementing it by setting timers on all the user events like onPress onSwipe etc on all the elements. But handling those is a complex process. Then I tried out using InteractionManager but that also didn't work out. What I want to know is there any way I can get to know if any user event has occurred?
By idle, I mean the user doesn't touch anything in the app. Normally, we use Touchable* to detect a user press event. But we cannot apply this on top of another element because it will override all touch event on the pages and your app won't be functional. After a brief research, I found that we can use PanResponder .
Define a function that takes the number of milliseconds as parameter. Use the setTimeout method to resolve a Promise after the provided number of milliseconds.
Let's see how we can implement the idle timeout feature in the React application with the react-idle-timer library. As a first step, we need to install react-idle-timer dependencies in the existing application. Once installed we have to import these modules in the Layout. js file.
Finally, I did it using PanResponder. And It works flawlessly. It takes key presses ans swipes and drags.
Expo Link : https://snack.expo.io/Sy8ulr8B-
Here is my code:
import React, { Component } from 'react';
import { Button, PanResponder, View, StyleSheet,TouchableOpacity, Text , Image} from 'react-native';
export default class App extends Component {
state = {
show : false
};
_panResponder = {};
timer = 0;
componentWillMount() {
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => {
this.resetTimer()
return true
},
onMoveShouldSetPanResponder: () => true,
onStartShouldSetPanResponderCapture: () => { this.resetTimer() ; return false},
onMoveShouldSetPanResponderCapture: () => false,
onPanResponderTerminationRequest: () => true,
onShouldBlockNativeResponder: () => false,
});
this.timer = setTimeout(()=>this.setState({show:true}),5000)
}
resetTimer(){
clearTimeout(this.timer)
if(this.state.show)
this.setState({show:false})
this.timer = setTimeout(()=>this.setState({show:true}),5000)
}
render() {
return (
<View
style={styles.container}
collapsable={false}
{...this._panResponder.panHandlers}>
{
this.state.show ? <Text style={{fontSize:30}}>Timer Expired : 5sec</Text> : null
}
<TouchableOpacity>
<Image style={{width: 300, height: 300}} source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} />
</TouchableOpacity>
<Button
title="Here is a button for some reason"
onPress={() => {}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ecf0f1',
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With