0

I am trying to use react query to call an api but am unable to pass props to the api url. the props get consoled but do not pass to the api endpoint

//useData.js
import { useQuery } from "@tanstack/react-query";
import Error from "./Components/Error";
const myBaseUrl =
  "http://api.weatherapi.com/v1/forecast.json?key=59e580ae2ccf422c9fd551122xxxx";
const myFetchFunction = async (key, latitude, longitude) => {
  console.log(latitude); //value gets consoled
  try {
    const res = await fetch(
      `${myBaseUrl}&q=${latitude},${longitude}&aqi=yes&days=7`
    );
    const datez = await res.json();
    return datez;
  } catch (err) {
    console.log(err);
    return <Error />;
  }
};
export const UseData = (key, latitude, longitude) => {
  const { isLoading, isError, data } = useQuery(
    ["myData", latitude, longitude],
    (key) => {
      myFetchFunction(key, latitude, longitude);
    },
    {
      cacheTime: 3600000,
    }
  );
  return { isLoading, isError, data };
};


//mainScreen.js
  //calling the custom hook 
  const { data, isLoading, isError } = UseData("myData", 34.16, 23.14);

What am I doing wrong?

  • You can press "F12" and then click on the network tab, after that re-run the program, you can investigate what parameter was passed to the server. – The KNVB Jun 09 '23 at 08:32

2 Answers2

0

You forgot to return fetching function

    (key) => {
      myFetchFunction(key, latitude, longitude);
    },

It should be

    (key) => {
      return myFetchFunction(key, latitude, longitude);
    },
Hoàng Huy Khánh
  • 1,071
  • 8
  • 16
0

I made a simple mistake of passing key as parameter but still including the actual key ie

export const UseData = (key, latitude, longitude) => {
  const { isLoading, isError, data } = useQuery(
    [key, latitude, longitude],                      //myData replaced with key
    () => myFetchFunction(key, latitude, longitude),
    {
      cacheTime: 3600000,
    }
  );
  return { isLoading, isError, data };
};