Skip to content

Commit

Permalink
add debounce for user input optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
Kellswork committed Jan 14, 2024
1 parent 943166a commit 7c02135
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/components/autoCompleteState.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import { useEffect, useRef, useState } from "react";
import ResponseData from "../utils/type";
import { FileteredData } from "../utils/api";
import { useDebounce } from "../utils/helpers";

const AutoCompleteState = () => {
const [searchText, setSearchText] = useState<string>("");
const [suggestions, setSuggestions] = useState<ResponseData[]>([]);
const [showSuggestions, setShowSuggestions] = useState<boolean>(false);
const [selectedSuggestion, setSelectedSuggestion] = useState<number>(-1);
const inputRef = useRef<HTMLInputElement>(null);
const debouncedInputValue = useDebounce(searchText, 300)

useEffect(() => {
(async () => {
const filteredData = await FileteredData(searchText);
const filteredData = await FileteredData(debouncedInputValue);
if (filteredData) {
setSuggestions(filteredData);
}
Expand All @@ -35,7 +37,7 @@ const AutoCompleteState = () => {
return () => {
document.removeEventListener("click", handleFocusOut);
};
}, [searchText]);
}, [debouncedInputValue]);

return {
searchText,
Expand Down
17 changes: 17 additions & 0 deletions src/utils/helpers.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useState, useEffect } from 'react';

export function highlightMatch( suggestion: string, inputValue : string) {
const index = suggestion.toLocaleLowerCase().indexOf(inputValue.toLocaleLowerCase());
Expand All @@ -14,4 +15,20 @@ export function highlightMatch( suggestion: string, inputValue : string) {
{afterMatch}
</>
);
}

export function useDebounce(inputValue: string, delay: number) {
const [debouncedValue, setDebouncedValue] = useState(inputValue);

useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(inputValue);
}, delay);

return () => {
clearTimeout(timer);
};
}, [inputValue, delay]);

return debouncedValue;
}

0 comments on commit 7c02135

Please sign in to comment.