Reputation: 369
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?
Upvotes: 0
Views: 2039
Reputation: 176
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
Upvotes: 1