4

I am trying to use lodash.throttling to limit the number of onPress calls in a Touchable Highlight, using the below codes, but none works :

 <TouchableHighlight
       onPress={throttle(this.onPressHandler,5000,{leading:true, trailing:false})}>

 <TouchableHighlight
       onPress={()=>throttle(this.onPressHandler,5000,{leading:true, trailing:false})}>

However, when I put a console.log in the "onPressHandler" function, I see that the function is being called multiple times even if I tap the TouchableHighlight in quick succession.

What am I missing?

user2473779
  • 711
  • 6
  • 18
  • 2
    Related to this post : https://stackoverflow.com/questions/23123138/perform-debounce-in-react-js – Dyo Jan 29 '18 at 12:21

3 Answers3

2

I got this working, thanks to Sebastien's answer to this question

The answer talks about React.js, but nonetheless the concepts are similar for React Native as well.

I added the below code to the constructor and mapped onPress to onPressHandler directly

this.onPressHandler = throttle(this.onPressHandler, 5000, {leading:true, trailing:false});
user2473779
  • 711
  • 6
  • 18
1

Another solution is to use the <Throttle> component in this package: https://github.com/gmcquistin/react-throttle. It works fine in React Native apps (I'm currently using it in one of mine).

Usage:

import { Throttle } from 'react-throttle';

<Throttle time="5000" handler="onPress">
    <TouchableHighlight onPress={this.onPressHandler} />
</Throttle>
Dave Koo
  • 463
  • 4
  • 12
0

Try to put a callback on your onPress method so that is not called automatically.

<TouchableHighlight
    onPress={() => throttle(this.onPressHandler,5000,{leading:true, trailing:false})}>
Isaac Sekamatte
  • 5,500
  • 1
  • 34
  • 40