英文:
how to conditionally call a RTK-query hook in a loop though we cant use it inside useEffect
问题
useEffect(() => {
const fetchServiceProducts = async () => {
if (isSuccess === true && data) {
for (let i = 0; i < data?.data.length; i++) {
const serviceid = data.data[i].service_id;
console.log(serviceid, "serviceid");
const { data: serviceProduct } = await useServicedataByidQuery(serviceid).refetch();
console.log(serviceProduct, "serviceata");
}
}
};
fetchServiceProducts();
}, []);
由于无法在回调中添加 RTKQ 钩子,您如何使这个可能,并在循环长度完成后调用我的查询并获取收集的数据?
英文:
useEffect(() => {
const fetchServiceProducts = async () => {
if (isSuccess === true && data) {
for (let i = 0; i < data?.data.length; i++) {
const serviceid = data.data[i].service_id;
console.log(serviceid, "serviceid");
const { data: serviceProduct } = await useServicedataByidQuery(serviceid).refetch();
console.log(serviceProduct, "serviceata");
}
}
};
fetchServiceProducts();
}, []);
As we can't add RTKQ hook inside a callback, how do I make this possible and call my query after the loop length is completed and get collected data?
答案1
得分: 1
你可能想使用查询的“懒惰”版本。这会返回一个可以随时调用的“触发器”函数。更多详情请参阅useLazyQuery。
示例:
const [trigger] = useLazyServicedataByidQuery(/* 查询选项 */);
useEffect(() => {
const fetchServiceProducts = async () => {
if (isSuccess && data) {
for (let i = 0; i < data?.data.length; i++) {
const serviceId = data.data[i].service_id;
console.log({ serviceId });
const { data: serviceProduct } = await trigger(serviceId);
console.log({ serviceProduct });
}
}
};
fetchServiceProducts();
}, []);
英文:
You likely want to be using the "lazy" version of the query. This returns a "trigger" function that can be called at-will. See useLazyQuery for more details.
Example:
const [trigger] = useLazyServicedataByidQuery(/* query options */);
useEffect(() => {
const fetchServiceProducts = async () => {
if (isSuccess && data) {
for (let i = 0; i < data?.data.length; i++) {
const serviceId = data.data[i].service_id;
console.log({ serviceId });
const { data: serviceProduct } = await trigger(serviceId);
console.log({ serviceProduct });
}
}
};
fetchServiceProducts();
}, []);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论