Utilizing setTimeout with onPressIn and onPressOut in TypeScript and react native

Recently diving into React Native and working on my debut app. I've created a button component that performs an action when tapped, and repeats the action when held down. Even though I implemented a simple logic for this functionality, I'm facing issues with it. When I hold the button down, it executes the action correctly but the console throws an error message:

"Please attach a method to this component"

The error message appears when I release the button, leading me to believe that the problem lies within the onPressOut event.

Here's the code snippet, apologies for the mix of Spanish language in the code :c

import { View, Text, StyleSheet } from "react-native";
import { Button } from "react-native-elements";

interface INTERFACE {
  accionMenos: () => void;
  accionMas: () => void;
  texto: string;
  titleBotonMenos: string;
  titleBotonMas: string;
}

const BotonTextoBoton = ({
  accionMenos,
  accionMas,
  texto,
  titleBotonMenos,
  titleBotonMas,
}: INTERFACE) => {
   let timer: NodeJS.Timeout;

  function addTimer(action: () => void) {
    action();

    timer = setTimeout(() => {
      addTimer(action);
    }, 100);
  }

  function eraseTimer() {
    clearTimeout(timer);
  }

  return (
    <View style={styles.viewContainer}>
      <View style={{ width: "15%", backgroundColor: "red" }}>
        <Button
          onPressIn={() => addTimer(accionMenos)}
          onPressOut={eraseTimer}
          title={titleBotonMenos}
        />
      </View>
      <Text style={{ margin: 3, fontSize: 20 }}>{texto}</Text>
      <View style={{ width: "15%" }}>
        <Button
          onPressIn={() => addTimer(accionMas)}
          onPressOut={eraseTimer}
          title={titleBotonMas}
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  viewContainer: {
    flexDirection: "row",
    justifyContent: "center",
    paddingTop: 30,
    alignItems: "center",
  },
});

export default BotonTextoBoton;

Answer №1

To ensure the Button component works properly, a onPress method must be included. Even if this method does nothing, it is important to have it defined. The absence of an onPress is the same as passing undefined.

<Button onPress={undefined} onPressIn={() => addTimer(accionMas)} onPressOut={eraseTimer} title={"Titlte"} />

If you omit the onPress, you will receive the error message

Please attach a method to this component
.

To resolve this issue, simply update the code as shown below.

<Button onPress={() => {}} onPressIn={() => addTimer(accionMas)} onPressOut={eraseTimer} title={"Titlte"} />

By providing the function () => {}, which performs no action, the error message will no longer appear.

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

How do I convert the ImagePicker type to Base64 in Ionic Capacitor?

I am currently developing an app using Ionic (Angular-based) along with Capacitor Plugins, specifically the Camera Plugin. The main feature I am working on involves allowing users to choose up to 5 images from their gallery. To accomplish this, I have impl ...

Retrieve a list of all file names within a designated directory using Angular

I am working on my Angular app and I need to list all the file names inside the assets folder. To achieve this, I am planning to utilize the npm library called list-files-in-dir https://www.npmjs.com/package/list-files-in-dir Here is the service impleme ...

Exploring the archives of PubNub within Angular5

I've been working on integrating PubNub history into my web app, but I'm currently only able to view it in the console. Here's what I have so far: pubnub.history( { channel: 'jChannel', reverse: false, ...

Include a control within a form based on the Observable response

I am looking to enhance my form by adding a control of array type, but I need to wait for the return of an Observable before mapping the values and integrating them into the form. The issue with the current code is that it inserts an empty array control e ...

Observable doesn't respond to lazy loaded module subscriptions

I am trying to understand why my lazy loaded module, which loads the test component, does not allow the test component to subscribe to an observable injected by a test service. index.ts export { TestComponent } from './test.component'; export { ...

No provider for aspnetcore-spa routing

I'm using the Yeoman aspnetcore-spa template with Angular 2. There are essentially 3 key files involved: app.module.client.ts app.module.server.ts app.module.shared.ts I have placed my Service in the providers section of app.module.client.ts and t ...

Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array. Please define ...

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

Include TypeScript in a single component within an already established Vue project

I've been working on a large Vue project and I want to integrate TypeScript into it. However, every time I try to do so, I run into a lot of errors that take weeks to fix. Instead of going through that, I'd like to find a way to add TypeScript to ...

What is the process for designing a personalized text input with a dashed border bottom for the information?

I would like to add a dashed border to the input of my TextInput in react-native, similar to the example shown here. This is the code I have so far: <TextInput maxLength={5} keyboardType={'numeric'} style={styles.numBox}></TextInput> ...

Error message in TypeScript with Puppeteer library: "Element not found"

Incorporating puppeteer-core as a dependency in my TypeScript project within Visual Studio 2019 has caused an issue during the build process. The error message displayed is shown by a red squiggly line under Element: https://i.stack.imgur.com/HfJCu.png ...

Steps to resolve the error "The value for '--target' option should be one of the following: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es201', 'esnext'."

I recently cloned an Angular application and encountered an error related to the "target" property in the tsconfig.json file within Visual Studio 2019. My Angular version is v16.1.4, with Typescript v5.1.6. I've attempted to resolve this issue by upda ...

Utilizing a string as an index in TypeScript

Struggling with the following code snippet: interface IStudentType { [key: `${Students}`]: IStudent | IStudentMaths| IStudentPhysics } The error message received is TS1268: An index signature parameter type must be 'string', &apos ...

Ways to sequentially execute API calls rather than concurrently

Update: Find the complete solution at the end of this answer. Consider the following code snippet: @Injectable() export class FileUploader { constructor(private http: Http) {} upload(url: string, file: File) { let fileReader: FileReader ...

Issue with Pagination in Angular 7: Functioning Error

I am having trouble with my pagination setup. I am struggling to understand how to properly pass this.total = res.totalPage; from the Component to the Service so that it can count the pages correctly. Currently, it is only displaying one page as shown in t ...

BrowserRouter - The type '{ children: Element; }' is not compatible with the type 'IntrinsicAttributes', as they do not share any properties in common

After upgrading to React version 18, I encountered a type error with the BrowserRouter component. Despite trying various approaches, I am unable to pinpoint the root of the problem. Here is the error that pops up during debugging: Overload 1 of 2, &a ...

steps for setting up firestore database

Hey there, I'm trying to retrieve data from Firestore within a cloud function. To initialize Firebase, I have a file called firebase.ts: import * as admin from "firebase-admin"; import { getFirestore } from "firebase-admin/firestore&quo ...

Having trouble retrieving an Enum within an Angular template?

I am trying to use an enum to read a property of an array. However, I encountered an error with the following code: <ng-container *ngFor="let elem of list"> <div class="ui-g-12 ui-sm-12 ui-md-12 ui-lg-12 ui-xl-12"> &l ...

TypeScript error: Cannot find property 'propertyName' in the 'Function' type

I encountered an issue with the TypeScript compiler when running the following code snippet. Interestingly, the generated JavaScript on https://www.typescriptlang.org/play/ produces the desired output without any errors. The specific error message I recei ...

Methods for invoking a JavaScript function from TypeScript within an Angular2 application

Hey there! I'm looking to execute a regular JavaScript function from a TypeScript file. Let's say I have a JavaScript file called test.js and it's been imported into the index.html of my application. Now, I want to invoke the test() functi ...