2

Here I've one scenario in which I have one array which has some items to add into the database via GraphQL mutation.

I'm sending that mutation in a loop, and it's working fine.

But when I check into my database some mismatch is happened let say I have 10 items in the array and request are made rapidly so what happed is only 2 or 3 items is added to the database.

  • The first solution I tried is using Promise.all but it does not work.
  • Second thing in my mind is to send the current index to that mutation and after it is successful then it will return me the same index so I send another item according to that but I am confused that how to send that index along with variables and If it takes that but doesn't know whether it will return me same or not.

I attaching some of my code snippets to get more idea:

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
     },
  });
Akash Chavda
  • 125
  • 9

2 Answers2

0

The problem is that you are not awaiting all these GraphQL mutations. Basically, you are sending multiple requests at once, even though a mutation returns a promise, which in turn translates into just a few of the products actually getting updated/created in the database. You should instead do like this:

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
     },
  });
Peter Malik
  • 403
  • 4
  • 14
0

After some of the head-scratching operations, I finally find one solution which is worked.

// 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);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Akash Chavda
  • 125
  • 9