I am creating idle timer in my app and I want to reset timer on each click, scroll and etc. It seems a nonsense to call my resetTimer()
function on every onPress event. In web I would do event listeners like: $(document).mousemove()
, $(document).mousedown()
, $(document).scroll()
and etc.
Any suggestions on having some top-level event listeners that could call resetTimer()
on any touch event in React native?
I am creating idle timer in my app and I want to reset timer on each click, scroll and etc. It seems a nonsense to call my resetTimer()
function on every onPress event. In web I would do event listeners like: $(document).mousemove()
, $(document).mousedown()
, $(document).scroll()
and etc.
Any suggestions on having some top-level event listeners that could call resetTimer()
on any touch event in React native?
2 Answers
Reset to default 6After a day of investigating rect-native code I found fbjs that contains TouchEventUtils
(facebook uses it in their react native tests), which allows to use different touch event state functions(onTouchMove(event)
, onTouchStart(event)
, onTouchEnd(event)
).
So what I did:
npm install fbjs --save
And simply added onTouchStart
to to my top level Root ponent that wrapps my routes, therefore I have all screens covered as I am using it on all screens/views wrapper.
So my code looks something like this:
/* rest of my imports */
import TouchEventUtils from 'fbjs/lib/TouchEventUtils';
class Root extends Component {
onTouchStart(){
//my code to properly reset session timer
}
render() {
return (
<View
onTouchStart={this.onTouchStart}
>
{/*My routes*/}
</View>
)
}
}
And thats it, that's the solution to accesing top level event listener and doing something on every event. I didn't dig deeper(as this was enough for my case), so I am not sure what object it gets and if it can help to identify any further properties(i.e. making logging of clicked elements).
I don't think there is an official API for this.
As a part of investigating how we could use Cycle.js with React Native, we did experiment on monkey patching the __fbBatchedBridge
global defined by the BatchedBridge module to listen to all global events ing in from the native side.
It was not suitable for us, because all we get are raw touch events, and it wasn't possible to filter for different kinds of event types. But if what you indeed want is to know when any touch event occurs, that solution might work for you.
It would, of course, be brittle and hacky :)