javascriptreactjsgraphqlreact-apollographql-tag

Make a mutation call multiple times depending on length of variable


Is there a way for me to call a mutation multiple times from the front-end? I have an array of users I need to add to an app and the mutation currently only allows to add one user at a time (we could change the mutation but they want to see if I can batch on the front end first).

This is my current mutation:

export const SHARE_APP = gql`
  mutation ShareApp(
    $appId: String!
    $userId: String!
  ) {
    shareApp(
      appId: $appId
      userId: $userId
    ) {
      updatedApp {
        id
      }
    }
  }
`;

Can this be done on the front-end or do I need to change the gql code to accept an array for ids?


Solution

  • The Mutation component, the useMutation hook and the graphql HOC all give you a method that can be used as many times as you like.

    const [share] = useMutation(SHARE_APP)
    await Promise.all(appIds.map((appId) => share({
      variables: {
        userId,
        appId,
      },
    })))
    

    As far as batching these requests, Apollo does not support that out of the box so you would have to use a link like apollo-link-batch-http.