Search code examples
reactjsreduxgraphqlredux-sagagraphql-mutation

How to make second GraphQL mutation after first one is completed in loop


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
     },
  });

Solution

  • 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);