0

I am currently working on a React project and facing issues when using the useQuery hook from react-query.

Here's what my code looks like:

import React from "react";
import Header from "./components/Header";
import SearchInput from "./components/SearchInput";
import SearchResult from "./components/SearchResult";
import { useQuery } from "@tanstack/react-query";
import axios from "axios";

const getDictionarySearch = async (searchTerm: string) => {
  return await axios.get(
    "cool/api/" + searchTerm
  );
};

function Main() {

  const { data, isError, isLoading } = useQuery({
    queryKey: ["searchResults"], ---> Getting error here.
    queryFn: getDictionarySearch,
  });

  const handleSearchTermChange = (results: string) => {
    console.log("search term:", results);
  };

  return (
    <div className="absolute w-full h-full bg-cream dark:bg-black">
      <div className="mx-auto max-w-3xl md:my-20 px-5 ">
        <Header />
        <SearchInput onSearchTermChange={handleSearchTermChange} />
        <SearchResult />
      </div>
    </div>
  );
}

export default Main;

enter image description here When using the useQuery function, I am passing an object as argument with queryKey and queryFn as properties. But it seems this might not be the correct way to pass these parameters because it's causing errors.

So, what is the correct way to use useQuery in this case? Any help would be greatly appreciated!

Sankalp Singha
  • 4,461
  • 5
  • 39
  • 58
  • change to `queryFn: () => getDictionarySearch(mySearchTerm)` and include `mySearchTerm` in your `queryKey`. you probably want `enabled: mySearchTerm != ""` too – Mulan Aug 26 '23 at 22:36

1 Answers1

0

queryFn needs to be a function with no arguments. So you need to change it to something like queryFn: () => getDictionarySearch(searchTerm).

With this setup searchTerm needs to be a state.

As mentioned in the comment you also would want to add search term to the query key, so that react-query can separate caches for various search terms. queryKey: ["searchResults", seatchTerm].

// searchTerm is a state
const [searchTerm, setSearchTerm] = useState();

const { data, isError, isLoading } = useQuery({
  // add searchTerm to the cache key
  queryKey: ["searchResults", searchTerm],
  // queryFn is a function with no arguments
  queryFn: () => getDictionarySearch(searchTerm),
});

const handleSearchTermChange = (results: string) => {
  // update the state by calling setSearchTerm which will trigger a new fetch
  setSearchTerm(results);
};
Anton
  • 1,045
  • 1
  • 7
  • 16