I’m currently working on implementing a search functionality using the React Query library in my application. While I have a basic implementation in place, I’m seeking advice on how to optimize the handling of search queries effectively.
hook:
// getAppointmentsSearchAsync function
async function getAppointmentsSearchAsync({ search }) {
let url = "/appointment/search";
if (search && search !== "") {
url = url + `?appointmentSearch=${search}`;
}
const { data } = await authFetch(url);
return data;
}
// useGetAppointmentsSearch hook
export function useGetAppointmentsSearch({
search,
debounce = 1500,
inputRef,
}) {
const debouncedSearchQuery = useDebounce(search, debounce);
if (inputRef.current) {
inputRef.current.focus();
}
const query = useQuery({
queryKey: ["appointments", debouncedSearchQuery ?? ""],
queryFn: () => getAppointmentsSearchAsync({ search: debouncedSearchQuery }),
keepPreviousData: true,
});
return query;
}
SearchPage component
const SearchPage = () => {
const [search, setSearch] = useState("");
const inputRef = useRef(null);
const navigate = useNavigate();
const { data, error, status } = useGetAppointmentsSearch({
search,
inputRef,
});
useEffect(() => {
const searchParams = new URLSearchParams(location.search);
const querySearchTerm = searchParams.get("search");
if (querySearchTerm) {
setSearch(querySearchTerm);
}
}, [location]);
const handleInputChange = (e) => {
setSearch(e.target.value);
navigate(`/appointments?search=${search}`);
};
return (
<div className="appointment-list search-list">
{status === "pending" ? (
<Loader />
) : status === "error" ? (
<span>Error: {error.message}</span>
) : data && data.appointments && data.appointments.length > 0 ? (
data.appointments.map((appointment, index) => (
<AppointmentItem key={index} {...appointment} />
))
) : (
<h3>No Appointment Data..</h3>
)}
</div>
);
};
export default SearchPage;
I expected that updating the query parameter on every keystroke might result in frequent server requests, potentially impacting the application’s performance.
By considering the integration of a debounce mechanism, I aimed to enhance the search experience by reducing the number of server requests while ensuring timely updates to the search results displayed to the user.
codercret company is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.