Tips for leveraging rxjs debounceTime with React Native's textInput component

I recently came across an example in Angular that showed how to replicate the debounceTime functionality from rxjs:

    fromEvent(this.input.nativeElement, 'keyup')
      .pipe(
        map(event => event.target.value),
        debounceTime(400),
        distinctUntilChanged(),
      )
      .subscribe(val => console.log(val));

Curious to try this out in React Native, I attempted my own replication:

export default function SearchScreen() {
  const [text, setText] = useState('');
  function onChangeHandler(event) {
    of(event)
      .pipe(
        map(event => event.nativeEvent.text),
        debounceTime(400),
      )
      .subscribe(val => console.log(val));
  }
  return (
    <View>
      <View>
        <TextInput
          value={text}
          onChangeText={text => setText(text)}
          onChange={onChangeHandler}
        />
      </View>
    </View>
  );
}

Unfortunately, I couldn't figure out how to adapt the fromEvent method for React Native, so I substituted it with of. However, despite my efforts, the debounceTime functionality is not working as expected.

Answer №1

Consider utilizing a Subject in place of changeHandler and eliminating the use of both onChangeText and value

let SearchScreenComponent = () => {
  const [text, setText] = useState('');
  const subject = new Subject();
  subject.asObservable()
      .pipe(
        map(event => event.nativeEvent.text),
        debounceTime(400),
      )
      .subscribe(val => console.log(val));
  
  return (
    <View>
      <View>
        <TextInput
          onChange={evt=>subject.next(evt)}
        />
      </View>
    </View>
  );
}
export default SearchScreenComponent;

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

The cascading menu causes interference with the function of other elements in the

I am currently designing a navigation bar that includes a drop-down menu (with plans to add another one in the future). The issue I'm facing is that when the user clicks on the drop-down menu, it shifts all of the navigation links to the right. What I ...

Trouble with sending data from jQuery Ajax to Node.js server

I am in the process of developing a video streaming platform that needs to constantly update the backend on the status of the videos being played. However, I am encountering an issue where the data sent through an ajax request appears as an empty object {} ...

Updating JSON data in Node.js by adding a new object

I'm facing a situation where I have a JSON file acting as a database to manage users by adding, removing, and modifying them. Currently, I have the following code snippet: 'use strict'; const fs = require('fs'); let student = { ...

Troubleshooting issue: Event-stream mapSync not functioning properly in async/await scenario

The await commands that I have marked as //******This await does not work */ do not appear to be functioning. It is unclear whether this issue is related to them being in an event stream or if it's a problem with the promise in the imported module. U ...

Error message: "When namedPlaceHolder parameter is disabled, bind parameters must be in the form of an

Currently revamping my query due to a crucial API redesign. With the presence of a "file" as multipart/form-data, I found the need for a form handler since NextJS lacked one. After some workarounds with "multiparty", now I can successfully parse the incomi ...

Guide to implementing a personalized filter in AngularJS 1.6

I am struggling with injecting a custom filter, status, into my component. Below is the code for my component: function ClaimsListController(dpClaimsListService) { var ctrl = this; ctrl.claims = null; ctrl.searchCriterion = null; ctrl.l ...

Syntax error in node/express: missing closing parenthesis after argument list

Just starting out with Node.js... const express = require('express'); const bodyParser= require('body-parser'); const MongoClient = require('mongodb').MongoClient; const app = express(); app.use(bodyParser.urlencoded({extend ...

Ionic utilized the $http service and was unexpectedly triggered two times

$scope.login = function(email,password){ $http({ method: 'POST', url: 'http://example.com/login', headers: { 'owner': $rootScope.secret }, data: {email:email, password:password } }).then(function successCallback(response) { co ...

Transform JSON time data from Coordinated Universal Time (UTC) to Indian Standard

Hello, I consider myself an amateur in the world of online javascript learning. Currently, I have come across a challenge that has left me stuck. I am working with a JSON time data provided in UTC format (e.g. 16:00:00Z) and my goal is to convert it to IS ...

Refresh Div/PartialView periodically

I have a function that performs an Ajax call, retrieves a result, and functions perfectly. @foreach (var fighter in Model.Fighters) { @Ajax.ActionLink(fighter.FirstName + " " + fighter.LastName, "ShowResults",new {id = fighter.FighterID }, new AjaxOptions ...

Embedding image URLs fetched from JSON data within <li> elements

I have successfully retrieved a JSON response, which is displayed using the code below: Within my HTML document, I have the following structure: <ol id="selectable"></ol> In my JavaScript code, I make use of the following: <script type=" ...

Encountering Issues with Loading Stripe Checkout Session Window

My register process involves a two-step procedure where a user fills out a web form to create a user account and then gets redirected to a Stripe checkout page for payment details. However, I'm encountering an issue with the Stripe Checkout window not ...

Encountering net::ERR_CONTENT_LENGTH_MISMATCH error while using Datatable with AJAX, JSON, and JQUERY

I'm utilizing the Datatables library to create a table that auto-refreshes from a JSON feed. While it is functioning correctly, I am encountering an error message every time the data in the table changes: Failed to load resource: net::ERR_CONTENT_LEN ...

Is there a way to extract the URL from an ng-resource?

Is there a way to retrieve the URL and parameters from an ng-resource object? If not, what are some strategies for creating a custom wrapper or extending ng-resource to achieve this functionality? Update: My goal is to extract the URL and params from the ...

Unable to insert JSON data into modal

I am facing an issue with appending Descriptions into modals after fetching data through axios. Each div contains a Category, and clicking on it should open a corresponding modal displaying the Description. Although I can see the Descriptions in the conso ...

Using HTTP POST to subscribe and implementing a try-catch block

When using Angular2's http.post, I encountered an issue where the headers were not sent to the CORS server. To address this, I attempted to create a loop that would retry the request until it succeeds. However, this resulted in an endless loop. How ca ...

Issue arises when attempting to submit multiple form fields with identical 'name' attributes, preventing the fields from being posted

Currently, I am facing a challenge with old HTML/JavaScript code. Some parts I have control over, while others are generated from an external source that I cannot manage. There is a form created dynamically with hidden fields. The form is produced using a ...

Zero displayed in AJAX response

Need some help with AJAX in WordPress. I'm encountering an issue where the response I get from AJAX is always showing as "0". https://i.sstatic.net/9j4SM.png function verifymsg() { var verifymobile = $('#verifymobile').val(); var otpmobile ...

Display a JavaScript object as a table in an HTML document using HTML elements

I am having trouble displaying the results of sorting an associative array in JavaScript in an HTML table without using PHP. The sorting itself is working correctly as I can see the results in the console, but the table is not showing up. Below is the code ...

Unable to activate IndexedDb persistence with Firebase v9 in a Next.js PWA

I'm having trouble enabling IndexedDb persistence in Firebase v9 for a Next.js PWA. These errors keep popping up: index.js // main Firebase file import { initializeApp } from 'firebase/app' import { getAuth } from 'firebase/auth' ...