user15395591
user15395591

Reputation: 273

React-Query, useQuery returns undefined only after loading is complete

I am using the react-query package in my react app. I have a pattern going which uses useQuery to get data from an api with axios. Multiple endpoints work except a GET search/params endpoint. Axios returns the expected data but once loading is complete in useQuery, undefined is returned.

import React from "react";
import { useQuery } from "react-query";
import { api } from "../../../api";

export const useSearch = (query) => {
  const searchResults = useQuery(
    api.clubhouse.searchCacheKey(query),
    api.clubhouse.search({ params: { query: query } })
  );

  let searchData = [];

  let isLoading = searchResults.isLoading;

  if (!isLoading) {
    searchData = searchResults.data;
  }

  return { searchData, isLoading };
};

Once isLoading: false, searchResults becomes undefined and I see this error TypeError: config.queryFn.apply is not a function. If I log inside the api.clubhouse.search (which contains the axios call) I can see the correct data. This pattern works fine for other api calls as well...

Upvotes: 1

Views: 2636

Answers (1)

Chris Farmer
Chris Farmer

Reputation: 25386

I'm guessing that this may be your issue:

api.clubhouse.search({ params: { query: query } })

The search function here I am guessing is returning a promise, but you need to pass in a function to useQuery that returns a promise instead of the promise itself. So, maybe make a change like this:

const searchResults = useQuery(
  api.clubhouse.searchCacheKey(query),
  () => api.clubhouse.search({ params: { query: query } })
);

Upvotes: 2

Related Questions