TanStackT
TanStack6mo ago
21 replies
hurt-tomato

UseQuery loading spinner showing right away! :(

hey guys im running into an issue where my useQuery ispending state is showing right away! even though im using enabled: false!

im triggering the query to run manually by using refetch()

but for some reason it shows the spinner instantly even though i havent called refetch() yet

heres some context: would gladly appreciate some help

  const {
    data: subreddits = [],
    isPending: isSubredditsPending,
    error: subredditsError,
    refetch,
  } = useSearchSubreddits(authFetch, isAuth?.id, searchTerm);

// custom hook
export function useSearchSubreddits(authFetch, userId, searchTerm) {
  return useQuery({
    queryKey: ["searchSubreddits", userId],
    queryFn: async ({ signal }) => {
      const res = await authFetch(
        `${import.meta.env.VITE_SERVER_URL}/api?q=${searchTerm.trim()}`,
        { signal },
      );
      const data = await res.json();
      if (!res.ok) {
        throw new Error("Failed to search subreddits");
      }
      return data;
    },
    enabled: false,
    staleTime: 0,
    gcTime: 0,
  });
}

// loading state check
 {/* Subreddit List */}
            <div className="overflow-y-auto flex flex-col flex-1 p-4 text-gray-500">
              {isSubredditsPending && searchTerm.trim() ? (
                // Loader
                <div className="flex justify-center items-center py-8">
                  <ImSpinner className="animate-spin text-2xl" />
                </div>


i previously had it as just isSubredditsPending that showed the spinner instantly but then i added searchTerm.trim()

and it didnt show it instantly but now as soon as i type a letter it shows the spinner even though i have clicked search button yet 🙁

heres my manual refetch call
  // search subreddits
  const handleSearch = async () => {
    if (!searchTerm.trim()) return;
    await refetch();
    setSearchTerm("");
  };


the search button triggers this!

i need some guidance as to what im doing wrong and how can i fix this 🙁
Was this page helpful?