我有两个API呼叫第二是取决于第一个API呼叫响应

发布于 2025-01-18 10:24:17 字数 430 浏览 1 评论 0原文

我想首先从地理定位 API 获取坐标,然后借助从第一个 API 调用获取的坐标获取天气状况。


   const { data: cords } = useQuery("cords", () => {
    navigator.geolocation.getCurrentPosition((position) => {
    });
   });

  const { isLoading, isError, error, data } = useQuery(["weather"], () => {
    return axios.get(
      `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=myapikey`
    );
  });

I want to get coordinates first from the geolocation API and then fetch weather conditions with the help of coordinates that I got from the first API call.


   const { data: cords } = useQuery("cords", () => {
    navigator.geolocation.getCurrentPosition((position) => {
    });
   });

  const { isLoading, isError, error, data } = useQuery(["weather"], () => {
    return axios.get(
      `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=myapikey`
    );
  });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦忆晨望 2025-01-25 10:24:17

对于第二个查询,您必须使用启用 用于依赖的操作员查询

您可以执行启用:!! CORDS,因此在有cords时将执行。

编辑:

在您的情况下,这是这样的:

  const { isLoading, isError, error, data } = useQuery(["weather"], () => {
    return (
      axios.get(
        `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=myapikey`
      ),
      {
        enabled: !!cords,
      }
    );
  });

这样,只有在cords具有值时,第二个查询才会触发,并且每次都会发射cords值,它已更新已更新。

For the second query you have to use the enabled operator for dependent queries.

You can do enabled: !!cords so it gets executed when there’s cords.

Edit:

In your case it'd be like this:

  const { isLoading, isError, error, data } = useQuery(["weather"], () => {
    return (
      axios.get(
        `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=myapikey`
      ),
      {
        enabled: !!cords,
      }
    );
  });

This way the second query will only fire when the cords have a value and it will fire every time cords value it's updated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文