首页 > 解决方案 > 如何使用反应查询在按钮单击时调用相关 API?

问题描述

我需要在按钮单击时调用 2 个 API,其中第二个查询取决于第一个查询,我需要将数据从第一个查询传递到第二个查询,我可以使用 javascript 函数来实现这一点,但我想使用“react-query”,因为我是肯定会有更少的代码,我会得到“isFetching”和“data”,下面是工作的javascript函数

const addGuestCart = () => {
    let getCartKey = new FormData();
    getCartKey.append('lang', 's001');
    let config1 = {
      method: 'post',
      url: 'first api_url',
      data: getCartKey,
    };
    axios(config1)
      .then(({ data }) => {
        console.log(data);
        return data;
      })
      .then((data) => {
        let guestCart = new FormData();
        guestCart.append('qty', '1');
        guestCart.append('lang', 's001');
        guestCart.append('sku', sku);
        guestCart.append('opid1', '0');
        guestCart.append('opvalue1', '0');
        guestCart.append('opid2', '0');
        guestCart.append('opvalue2', '0');
        guestCart.append('productid', id);
        guestCart.append('cartid', data.cartid);
        guestCart.append('key', data.key);

        let config2 = {
          method: 'post',
          url: 'second api_url',
          data: guestCart,
        };
        axios(config2).then((res) => {
          console.log(res);
          // return res;
        });
      });
  };

任何帮助将不胜感激 :)

标签: javascriptreactjsaxiosreact-query

解决方案


文档中有此用例的示例:https ://react-query.tanstack.com/guides/dependent-queries

// Get the user
 const { data: user } = useQuery(['user', email], getUserByEmail)
 
 const userId = user?.id
 
 // Then get the user's projects
 const { isIdle, data: projects } = useQuery(
   ['projects', userId],
   getProjectsByUser,
   {
     // The query will not execute until the userId exists
     enabled: !!userId,
   }
 )
 
 // isIdle will be `true` until `enabled` is true and the query begins to fetch.
 // It will then go to the `isLoading` stage and hopefully the `isSuccess` stage :)

推荐阅读