axios 当搜索字符串为空时,如何阻止react-query发送搜索请求?

kokeuurv  于 2023-08-04  发布在  iOS
关注(0)|答案(1)|浏览(101)

我使用Tanstack React Query来获取一个城市列表,该列表基于react 18 + typescript应用程序中输入框(天气应用程序的搜索功能)中键入的内容。我使用去抖动状态并将初始值设置为空字符串。但是react-query发送空字符串的请求,导致多个不成功的请求,错误400(显示在浏览器控制台),你不能把钩子放在if语句中,所以我该怎么办?

如果搜索词(去抖状态)长度超过2个字符,我想发送请求。

搜索框组件:

import { TextInput } from "@mantine/core";
import { useDebouncedState } from "@mantine/hooks";

import useSearch from "../hooks/useSearch";

const SearchBox = () => {
  const [searchTerm, setSearchTerm] = useDebouncedState("", 400);
  const { data: suggestedCities, isError, isLoading } = useSearch(searchTerm);

  if (isLoading) <h1>Loading...</h1>;
  if (isError) <h1>Failed to fetch cities list!</h1>;

  return (
    <div>
      <TextInput
        defaultValue={searchTerm}
        onChange={(event) => setSearchTerm(event.currentTarget.value)}
      />
    </div>
  );
};

字符串

使用Search自定义钩子来获取数据:

import { useQuery } from "@tanstack/react-query";
import axios from "axios";

const fetchCitiesList = async (searchTerm: string) => {
  const options = {
    method: "GET",
    url: "https://weatherapi-com.p.rapidapi.com/search.json",
    params: { q: searchTerm },
    headers: {
      "X-RapidAPI-Key": import.meta.env.VITE_WEATHER_API_KEY,
      "X-RapidAPI-Host": import.meta.env.VITE_WEATHER_API_HOST,
    },
  };

  const { data } = await axios.request(options);
  return data as City[];
};

const useSearch = (searchTerm: string) => {
  return useQuery({
    queryKey: ["search-city", searchTerm],
    queryFn: () => fetchCitiesList(searchTerm),
  });
};

export default useSearch;

浏览器控制台显示:

x1c 0d1x的数据

oxiaedzo

oxiaedzo1#

可以在查询中使用enabled,如,这将使查询仅在值为true时执行

return useQuery({
    enabled: !!searchTerm
    queryKey: ["search-city", searchTerm],
    queryFn: () => fetchCitiesList(searchTerm),
  });

字符串
https://tanstack.com/query/v4/docs/react/reference/useQuery

相关问题