0

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.

2
  • As you have keepPreviousData: true, you may want to keep displaying previous results when loading new results, instead of only showing the Loader. But other than that, what optimization are you looking for? Commented May 12, 2024 at 22:04
  • i want to make sure that im using debounce correctly along with pushing the current search to url query Commented May 13, 2024 at 23:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.