Why doesn't my debounce function work in a React app with hooks?


rookie

My goal is to trigger a fetch request to fetch data from the API after some delay. In my particular case, I have an input field where the user can enter the post ID. I don't want to trigger a fetch request on every number entered in the input field. I only want to make the request 1 second after the user has stopped entering data. Here is my implementation:

import { useCallback, useEffect, useState } from 'react'
import './App.css'

function debounce(fn, ms) {
  let timeoutId
  return function (...args) {
    if (timeoutId) clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      fn(...args)
    }, ms)
  }
}

function App() {
  const [input, setInput] = useState('')

  const fetchData = async () => {
    if (input !== '') {
      let res = await fetch(`https://jsonplaceholder.typicode.com/posts/${input}`)
      let resData = await res.json()
      console.log(resData)
    }
  }

  const fireRequest = useCallback(debounce(fetchData, 1000), [])

  useEffect(() => {
    fireRequest()
  }, [input])

  return (
    <div className='App'>
      <input type='text' onChange={(e) => setInput(e.target.value)} value={input}></input>
    </div>
  )
}

export default App

For some reason it doesn't work. There are no errors, and it doesn't appear to be getting my data (no logging whatsoever to the console). What am I doing wrong? thanks.

Rajat Jain

The main problem here is that the function is only called when input != "". The function does not become a no-op until the input is not set to the desired value. However, this change will help

import { useCallback, useEffect, useState } from 'react'
import './App.css'

function debounce(fn, ms) {
  let timeoutId
  return function (...args) {
    if (timeoutId) clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      fn(...args)
    }, ms)
  }
}

export default function App() {
  const [input, setInput] = useState('')

  const handleInputChange = (e) => {
    setInput(e.target.value);
    debouncedFireRequest(e.target.value);
  };

  const debouncedFireRequest = useCallback(
    debounce(async (value) => {
      if (value !== '') {
        let res = await fetch(`https://jsonplaceholder.typicode.com/posts/${value}`)
        let resData = await res.json()
        console.log(resData)
      }
    }, 1000),
    []
  );

  return (
    <div className='App'>
      <input type='text' onChange={handleInputChange} value={input}></input>
    </div>
  );
}

Related


Why doesn't my debounce function work in a React app with hooks?

rookie My goal is to trigger a fetch request to fetch data from the API after some delay. In my particular case, I have an input field where the user can enter the post ID. I don't want to trigger a fetch request on every number entered in the input field. I o

Why doesn't my debounce function work in a React app with hooks?

rookie My goal is to trigger a fetch request to fetch data from the API after some delay. In my particular case, I have an input field where the user can enter the post ID. I don't want to trigger a fetch request on every number entered in the input field. I o

Why doesn't my debounce function work in a React app with hooks?

rookie My goal is to trigger a fetch request to fetch data from the API after some delay. In my particular case, I have an input field where the user can enter the post ID. I don't want to trigger a fetch request on every number entered in the input field. I o

Why doesn't my debounce function work in a React app with hooks?

rookie My goal is to trigger a fetch request to fetch data from the API after some delay. In my particular case, I have an input field where the user can enter the post ID. I don't want to trigger a fetch request on every number entered in the input field. I o

Why doesn't debounce call my function?

Youku I am using React and mobx to do something . I've created an ImageCarousel component that displays the clicked image. I have a previous and a next button (which are themselves a component) for moving between images. I've tried wrapping these operations (

Lodash's debounce doesn't work in React

user818700: Better to have a look at my code first: import React, { Component } from 'react'; import _ from 'lodash'; import Services from 'Services'; // Webservice calls export default class componentName extends Component { constructor(props) { super(

Lodash's debounce doesn't work in React

user818700: Better to have a look at my code first: import React, { Component } from 'react'; import _ from 'lodash'; import Services from 'Services'; // Webservice calls export default class componentName extends Component { constructor(props) { super(

Lodash's debounce doesn't work in React

user818700: Better to have a look at my code first: import React, { Component } from 'react'; import _ from 'lodash'; import Services from 'Services'; // Webservice calls export default class componentName extends Component { constructor(props) { super(

Lodash's debounce function doesn't work

GN。 const { debounce } = require('lodash'); debounce( () => { console.log('testing..'); }, 1000, { leading: true, trailing: false } ); The code above doesn't work. All examples in the documentation at https://lodash.com/docs/4.17.4#debounce use

Lodash's debounce function doesn't work

GN。 const { debounce } = require('lodash'); debounce( () => { console.log('testing..'); }, 1000, { leading: true, trailing: false } ); The code above doesn't work. All examples in the documentation at https://lodash.com/docs/4.17.4#debounce use

Lodash's debounce function doesn't work

GN。 const { debounce } = require('lodash'); debounce( () => { console.log('testing..'); }, 1000, { leading: true, trailing: false } ); The code above doesn't work. All examples in the documentation at https://lodash.com/docs/4.17.4#debounce use

Lodash's debounce function doesn't work

GN。 const { debounce } = require('lodash'); debounce( () => { console.log('testing..'); }, 1000, { leading: true, trailing: false } ); The code above doesn't work. All examples in the documentation at https://lodash.com/docs/4.17.4#debounce use

Lodash's debounce function doesn't work

GN。 const { debounce } = require('lodash'); debounce( () => { console.log('testing..'); }, 1000, { leading: true, trailing: false } ); The code above doesn't work. All examples in the documentation at https://lodash.com/docs/4.17.4#debounce use

Why doesn't my app work in the emulator?

outdated Whenever I try to run my app in the Androidemulator , my app doesn't show up. I got this errorbut I'm having a hard time deciphering it. How can I fix this so that I can see my app in the emulator? I think it has something to do with my line of code b

Fontawesome doesn't work in my React app

Dinosaur I installed font-awesome via npm. "dependencies": { "@fortawesome/fontawesome-svg-core": "^1.2.15", "@fortawesome/free-solid-svg-icons": "^5.7.2", "@fortawesome/react-fontawesome": "^0.1.4", "axios": "^0.18.0",

My React app doesn't recognize useState and useRef hooks

Mihail OLARU enter image description here enter image description here Any ideas why I am getting this error? Weblandtk This is because we have a naming convention in place React. will be pomodoroAppchanged to PomodoroApp. React Hookscan only be used in Custom

My React app doesn't recognize useState and useRef hooks

Mihail OLARU enter image description here enter image description here Any ideas why I am getting this error? Weblandtk This is because we have a naming convention in place React. will be pomodoroAppchanged to PomodoroApp. React Hookscan only be used in Custom

My React app doesn't recognize useState and useRef hooks

Mihail OLARU enter image description here enter image description here Any ideas why I am getting this error? Weblandtk This is because we have a naming convention in place React. will be pomodoroAppchanged to PomodoroApp. React Hookscan only be used in Custom

My React app doesn't recognize useState and useRef hooks

Mihail OLARU enter image description here enter image description here Any ideas why I am getting this error? Weblandtk This is because we have a naming convention in place React. will be pomodoroAppchanged to PomodoroApp. React Hookscan only be used in Custom

My React app doesn't recognize useState and useRef hooks

Mihail OLARU enter image description here enter image description here Any ideas why I am getting this error? Weblandtk This is because we have a naming convention in place React. will be pomodoroAppchanged to PomodoroApp. React Hookscan only be used in Custom