Unable to pass params in react tanstack query

726 views Asked by At

I am trying to cache the data from google places Api using tanstack query but whenever I pass params I get this error

TypeError: client.defaultQueryOptions is not a function. (In 'client.defaultQueryOptions(options)', 'client.defaultQueryOptions' is undefined)

//my App.js

const queryClient = new QueryClient({
  defaultOptions: { queries: { retry: 2 } },
});
export default function App() {
  return (
    <GestureHandlerRootView style={{ flex: 1 }} onLayout={onLayoutRootView}>
      <QueryClientProvider client={queryClient}>
      ...all components
      </QueryClientProvider> 
}

my useData hook in maps.js

import { useQuery } from "@tanstack/react-query";
const baseUrl = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=${process.env.EXPO_PUBLIC_mapKey}`;
const myFetchFunction = async ({ queryKey }) => {
  const [_key, latitude, longitude, keywrd] = queryKey;
  try {
    const res = await fetch(
      `${baseUrl}&keyword=${keywrd}&location=${latitude}%2C${longitude}&radius=1500`
    );
    const { data } = await res.json();
    return data;
  } catch (err) {
    throw err;
  }
};
export const UseData = (key, latitude, longitude, keywrd) => {
  const { isLoading, isError, data } = useQuery(
    {
      queryKey: ["waste", latitude, longitude, keywrd],
      queryFn: ()=>myFetchFunction(latitude, longitude, keywrd),
    },
    {
      staleTime: 2592000000,
    }
  );

  return { isLoading, isError, data };
};

the component where I want to use the data where location is a stte with my coords

if (location) {
    const { isLoading, isError, data } = UseData(
      "DW",
      location.coords.latitude,
      location.coords.longitude,
      "waste"
    );
    if (!isLoading && data) console.log(data);

Can someone tell me how to correct this code

1

There are 1 answers

1
Kartic Joshi On BEST ANSWER

I was writing syntax according to react query v4 and in v5 options are part of the same object. Refactored the code like this

async function fet(...args) {
    try {
      const res = await fetch(...args);
      return await res.json();
    } catch (err) {
      throw err;
    }
  }

const { data, isLoading, isError } = useQuery({
    queryKey: ["Dwaste", latitude, longitude, keywrd],
    queryFn: () =>
      fet(
        `${baseUrl}keyword=${keywrd}&location=${latitude}%2C${longitude}&radius=1500&key=${process.env.EXPO_PUBLIC_mapi}`
      ),
    staleTime: 2592000,
  });