[SOLVED] Using a variable as an graphQL operation name in Apollo Client


I am connecting to a graphQL endpoint, to get the number of reactions(e.g. like, love, etc) on various content items on the page. The content items are identified by GUIDs.
The endpoint does not support fetching reactions for an array of GUIDs, so I am using batched queries instead, with a batch size of 20.
In this case, the endpoint requires that each query in a batch has a unique operation name.
How do I pass the GUID into the GQL query?

Here is my function call:

export const getReactionsByObjectIdsEngagement = async (
  objectIds: string[],
  apolloClient: ApolloClient<NormalizedCacheObject>
): Promise<IReaction[]> => {
  const results: IReaction[] = [];
  objectIds.forEach(async (contentId) => {
    await apolloClient
        query: GET_REACTIONS_QUERY_IP(contentId),
        variables: { contentId: contentId },
        context: {
          clientName: EngagementClientName,
          headers: {
            'content-type': 'application/json',
        errorPolicy: 'ignore',
      .then((data) => {
        const result: IReaction = {
          Id: contentId,
          Reactions: {
            Cool: data.data.getReactionsQuery.cool,
            Like: data.data.getReactionsQuery.like,
            LOL: data.data.getReactionsQuery.lol,
            Love: data.data.getReactionsQuery.love,
            Magic: data.data.getReactionsQuery.magic,
            Party: data.data.getReactionsQuery.party,
            Wow: data.data.getReactionsQuery.wow,
            YouRock: data.data.getReactionsQuery.youRock,
      .catch((error) => {

  return results;

And the related query:

export const GET_REACTIONS_QUERY_IP = (contentId: string) => {
  return gql`
    query getReactionsQuery($contentId: ID!) {
      "${contentId}": reactionsCount(contentId: $contentId) {

I have got the interpolation itself to work, but the request does not fire off successfully, because the Apollo client encounters an unexpected number or string in Name.
Initially I thought that it was because I failed to escape something in GUID, so I tried generating a random number in Typescript and passing it into the query.
Again, the passing in works, but I get the same error in Apollo (‘Expected Name, got myQuery_99").

Apollo client error

Batching works fine with the forEach loop, the request shows as expected in the Developer Tools Network tab in the browser.

Help a junior deliver some good news on the next daily. Thanks in advance!


If you end up here: the issue was an extra set of quote marks around my variable in the query: "${contentId}" should be ${contentId}..

Answered By – apetriceanu

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *