Implementing a long-press feature to increment a counter in React Native

Next to my TextInput, there is a button that increments its counter each time it's pressed.

   <TouchableWithoutFeedback onPress={() => {this.increaseAmount(step, rowID)}}>
      <View style={styles.amountPlusButtonContainer}>
        <Text style={styles.amountButtonText}>+</Text>
      </View>
    </TouchableWithoutFeedback>

Currently, the counter goes up by 1 with every tap of the button. I want to change it so that the counter continues to increase as long as the user holds down the button.

I attempted to solve this issue by using setInterval(), but I'm unsure of when to stop it or if this is the correct approach for this problem.

Answer №1

In my opinion, utilizing the setInterval function is a viable solution. Simply trigger setInterval during onPressIn and stop it with clearInterval upon onPressOut.

Answer №2

By utilizing the Animated API, I successfully implemented the functionality. In addition to consulting the official documentation, I also found guidance from a helpful resource at

   var ACTION_TIMER = 3000;
   var listenerActive = true;

   getInitialState(){
     return{
       pressAction: new Animated.Value(0),
       value: 0,
     };
   },
   componentWillMount: function() {
     this.state.pressAction.addListener((v) => this.setState({value: v.value}));
   },
   handlePressIn: function() {
     if(!listenerActive) {
       this.state.pressAction.addListener((v) => this.setValueAndChangeAmount(v.value));
       listenerActive = true;
     }
     Animated.timing(this.state.pressAction, {
         duration: ACTION_TIMER,
         toValue: 67,
     }).start();
   },
   handlePressOut: function() {
     this.state.pressAction.removeAllListeners();
     this.setState({pressAction: new Animated.Value(Math.ceil(this.state.value))});
     listenerActive = false;
   },

To maintain consistency with onPress, I relied on a timer of 3000ms and utilized Math.ceil in my implementation due to restrictions on using onPressInand onPressOut simultaneously.

The action of removing the listener in handlePressOut halts the counter. By setting a new pressAction with the current this.state.value, the value resets to where the counter was stopped.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Only dispatch to props upon being clicked

I am encountering an issue with the mapDispatchToProps function being sent as a whole, rather than only when I click on the delete button. My class successfully fetches the list data and everything works as expected. However, upon adding the delete button ...

How can React be used to constantly update a string whenever a checkbox is ticked, and subsequently show this updated string in a separate input field

I need to dynamically update a text input field each time a checkbox is checked as true. Could someone provide guidance on how to achieve this? My goal is to have a checkbox trigger an update in another input field. When the checkbox is checked, I want to ...

Running code sequentially in a Node.js controller

Recently delved into the world of Node.js, and I'm currently tackling the challenge of running this code synchronously in my controller. Quest.js async function create(req, res, next) { const formValue = req.body['form']; ...

React frontend GraphQL client unable to properly subscribe

I recently integrated a websocket into my React app and successfully handled the back-end portion with nodejs, utilizing GraphQL playground. However, I'm facing issues with getting subscriptions to work on the client side. Despite following the docum ...

Attempting to switch between panels while simultaneously updating the icon to display as 'show more' and 'show less'

As a beginner in jQuery/javascript, I have encountered what seems like a basic issue that is bothering me. In my project, I have a panel containing 6 <li> elements, with 3 initially hidden until the user clicks on the 'view more' link. Upo ...

What is the best way to access the element menu with element-ui?

I am looking for a way to programmatically open an element in my menu, but I haven't been able to find any information on how to do it. HTML <script src="//unpkg.com/vue/dist/vue.js"></script> <script src="//unpkg.com/<a hr ...

Exploring the asynchronous for loop functionality in the express.js framework

I'm attempting to use a for loop to display all images. I have stored the paths of the images in an array called Cubeimage. However, when trying to display them using <img>, I encountered an error. How can I write asynchronous code to make it wo ...

When working with three.js, I am able to successfully display a .glb 3D model locally. However, when trying to view it on the GitHub server

While working on my personal webpage, I attempted to use three.js to showcase a 3D model. The model appeared successfully on my local server, but failed to display on my web server, resulting in an error message similar to the following: https://i.sstatic. ...

iOS Simulator offers a range of both offline and online events for testing purposes

I have been working on a phonegap 3.3 application that incorporates angularjs. When testing the application in my browser, I am successfully able to detect and respond to 'offline' and 'online' events. However, when I switch to the ios ...

Attempting to retrieve AJAX response in JavaScript by utilizing an OOP object

Here is the code snippet I am working with: function CreateDiv(D) { D.body = function () { var d = $.ajax({ type: "GET", url: "Default.aspx", data: 'Ext ...

Node.js Objects and String Manipulation

Within my nodeJS scenario, I am working with an object that includes both elements and an array of items: var Obj = { count: 3, items: [{ "organizationCode": "FP1", "organizationName": "FTE Process Org" }, { "organizationCode ...

Encountering issues with uploading Cloudinary images through Nodejs

I'm having trouble uploading a base64encoded image to Cloudinary using the code snippet below. It's not working as expected and I keep getting a 500 error when making the post request. Can anyone provide me with a solution or suggest what might b ...

Using Placeholder in JavaScript for Multiple Form Validations

I am currently facing an issue with my form validation. It checks each input to determine if it is valid or not, but the problem arises when only one input is valid, as all inputs are then considered valid. I have tried moving the return true statement, bu ...

When the Angular UI Bootstrap typeahead ng-model is cleared, it displays as null

The filter is performing admirably, however, after deleting the entered text, the {{filterlist.name}} displays null. This leads to the tables appearing empty due to the presence of null. Check out the demo here: https://plnkr.co/edit/1QVdctw1hr4ggJOtFHUZ? ...

Creating a React.js component and setting an initial value within it

Recently delved into the world of React.js and currently attempting to create a reusable header that can switch between two states: one for when the user is logged in, and another for when the user is not logged in. // Header.js var Header = React.createC ...

Heroku - Launch your code in development or live environments

I am currently hosting my express API on Heroku with two separate projects set up: one for my Master Branch (Prod) and the other for my Development branch (Dev). Inside my package.json file, I have defined two scripts: "scripts": { "d ...

Storing session data for each HTTP request in a "global" variable using NodeJS

Linking back to a thread that is two years old where the topic aligns closely with what I am looking for. In the realm of C# development, there exists a Session object that holds user session information and can be accessed from any location. This object ...

There seems to be an issue with the post request to a PHP file as it is returning a null value when

I have been struggling with this issue for a while now and can't seem to understand why I keep getting null after calling my $.ajax function. I pass an associative array containing the method name, then invoke the method in PHP to return a JSON string ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

Prevent $.ajax with jQuery when a button is clicked

Is there a way to interrupt the $.ajax() function execution by clicking on this button: <button class="stop">Stop</button> Is there a specific function that can cause the $.ajax() call to stop? Note: The $.ajax script is within a function, l ...