0

I am trying to use useDebounce when user search a user in search function. How can I add useDebounce in this situation?

import { useDebounce } from "use-debounce";
const [searchQuery, setSearchQuery] = useState("");
const [invitees, setInvitees] = useState([]);

  const handleChange = (event) => {
    event.preventDefault();
    setSearchQuery(event.target.value);
  };

  const getUserToInvite = async () => {
    const res = await axios.get(
      `/api/v1/search/users/invite/${searchQuery}/${teamId}`
    );
    setInvitees(res.data[0]);
    setShowInvitees(!showInvitees);
  };

  useEffect(() => {
    if (searchQuery === "") {
      setInvitees([]);
    }

    if ((searchQuery || "").length >= 2) {
      getUserToInvite();
    }
  }, [searchQuery]);


          <input
            className="invitees--search_input"
            type="text"
            name="name"
            onChange={handleChange}
            placeholder="Name"
            aria-label="Search bar"
            pattern="^[a-zA-Z0-9 ]+"
            required
          />

How do you perform debounce in React.js?

nathan
  • 369
  • 2
  • 14
  • My guess is you use searchQuery for [useDebounce](https://github.com/xnimorz/use-debounce) first argument and run an effect on the resulting value. Debouncing does not guarantee the order of resolve is the same as the order of requests made so your UI an get [out of sync](https://stackoverflow.com/a/62751846/1641941) – HMR May 20 '21 at 16:23

1 Answers1

1

I think you can handle that by simply debouncing the value. So something like

const [searchQuery, setSearchQuery] = useState("");
const debouncedSearchQuery = useDebounce(searchQuery, 500)

useEffect(() => {
    if (debouncedSearchQuery === "") {
      setInvitees([]);
    }

    if ((debouncedSearchQuery || "").length >= 2) {
      getUserToInvite();
    }
  }, [debouncedSearchQuery]);

If you are looking to debounce the callback, that is a little different. But the use-debounce docs do a great way of explaining it! https://github.com/xnimorz/use-debounce#debounced-callbacks

  • I changed it to your code but im getting error `invitees.filter(...) is not a function` – nathan May 20 '21 at 16:31
  • How can I fix this problem ? – nathan May 20 '21 at 16:55
  • That leads me to believe that `invitees` is not an array... it's hard to tell why/where from just the code sample but is there any way that `res.data[0]` does not return an array? That's the only place in your sample i can see that you set the `invitees` state to something other than an empty array. – babycourageous May 21 '21 at 19:03