[英]How to make second GraphQL mutation after first one is completed in loop
在這里,我有一個場景,其中我有一個數組,其中有一些項目要通過 GraphQL 突變添加到數據庫中。
我正在循環發送該突變,它工作正常。
但是當我檢查我的數據庫時發生了一些不匹配,假設我在數組中有 10 個項目並且請求被快速提出,所以發生的只是 2 或 3 個項目被添加到數據庫中。
Promise.all
但它不起作用。index
,因此我根據該索引發送另一個項目,但我很困惑如何將該index
與variables
一起發送,如果它需要它,但不知道它是否會返回相同的結果。我附上了我的一些代碼片段以獲得更多想法:
import { useMutation } from "@apollo/client";
// Req in loop
const updateDataInLoop = (cartId, strapiId) => {
for (let i = 1; i < items.length; i++) {
updateReq({
variables: {
// API variables
},
});
}
};
// graphql api
const [updateReq] = useMutation(UPDATE_MUTATION, {
onCompleted: (data) => {
// after this I've to send another req
},
});
問題是您沒有等待所有這些 GraphQL 突變。 基本上,您一次發送多個請求,即使突變返回 promise,這反過來又轉化為實際上在數據庫中更新/創建的幾個產品。 你應該這樣做:
import { useMutation } from "@apollo/client";
// Req in loop
const updateDataInLoop = (cartId, strapiId) => {
for (let i = 1; i < items.length; i++) {
updateCartMutation(variable)
}
};
//make an async mutation
const updateCartMutation=async (variable)=>await updateReq({
variables: {
// API variables
},
});
// graphql api
const [updateReq] = useMutation(UPDATE_MUTATION, {
onCompleted: (data) => {
// after this I've to send another req
},
});
經過一些令人頭疼的操作,我終於找到了一種可行的解決方案。
// Req in loop
const updateDataInLoop = async (cartId, strapiId) => {
for (let i = 1; i < items.length; i++) {
try {
await updateReq({
variables: {
// API variables
},
});
continue;
} catch e {
break;
}
}
};
// graphql api
const [updateReq] = useMutation(UPDATE_MUTATION);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.