Home > other >  React - start searching when the user stops typing
React - start searching when the user stops typing

Time:05-02

I have searchInput in my app to search between an array of objects. I want to start searching when the user stops typing. Where is better to clear the timeout? and how?

this is my searchInput:

<input
  value={this.state.searchInput}
  id="searchInput"
  onChange={this.inputsChangedHandler}
/>

contacts is my main state. searchedContact should display when the user stops typing.

  inputsChangedHandler = (e) => {
    let searched = this.state.contacts.filter((i) => {
      return (
        i.numbers.includes(e.target.value) ||
        i.name.includes(e.target.value) ||
        i.family.includes(e.target.value)
      );
    });
    this.setState(
      {
        [e.target.id]: e.target.value,
      },
      () => {
        setTimeout(() => {
          this.setState({
            searchedContact: searched,
          });
        }, 2000);
      }
    );
  };

CodePudding user response:

check this answer click here

unction Search() {
  const [searchTerm, setSearchTerm] = useState('')

  useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      console.log(searchTerm)
      // Send Axios request here
    }, 3000)

    return () => clearTimeout(delayDebounceFn)
  }, [searchTerm])

  return (
    <input
      autoFocus
      type='text'
      autoComplete='off'
      className='live-search-field'
      placeholder='Search here...'
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  )
}

CodePudding user response:

I have write my own custom hook , useTrottle - like this

import {useState, useDebugValue} from 'react';
    const useThrottle = (func, delay) => {
    const [timeout, saveTimeout] = useState(null);
    useDebugValue(delay);
    const throttledFunc = function () {
        if (timeout) {
            clearTimeout(timeout);
        }

        const newTimeout = setTimeout(() => {
            func(...arguments);
            if (newTimeout === timeout) {
                saveTimeout(null);
            }
        }, delay);
        saveTimeout(newTimeout);
    }

    return throttledFunc;
}

export default useThrottle;

you can use this hook on your components by this way

const throttle = useThrottle((term) => {
    // make what you want
}, THROTTLE_DELAY);

const changeHandler = useCallback((event) => {
        setTerm(event.target.value);
        throttle(event.target.value);
    }, [throttle,setTerm])
  • Related