javascript - 如何使用反应查询在按钮单击时调用相关 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;
});
});
};
任何帮助将不胜感激 :)
解决方案
文档中有此用例的示例: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 :)
推荐阅读
- python-3.x - Python - Telnet 或 SSH 多个设备
- c++ - 避免堆栈溢出 C++
- mysql - 有没有办法使用logstash加入两个不同数据源(即Mysql和Postgres SQL)的数据库并将其索引到弹性搜索?
- java - 如何在 SpringBoot 中使用列表参数?
- python - 在 seaborn 中使用 sns.relplot.set 控制美学
- angular - 使用 fakeAsync 区域时如何为 ag-Grid 编写 Angular 测试?
- go - 服务器是否需要是指针
- postgresql - Postgres - 读取日期之前或之后的日期索引 (<, <=, >, >=)
- kentico-12 - Kentico v12 webpart 内容未正确导入
- python - 如何在 stan/pystan 中包含数据测量不确定性