2
votes

I'm new to graphql and having a issues on calling multiple graphql queries at once.

For example I have a query and it has to be called 3 times using different variables as I need all the data returned on page initial load.

For that I'm doing something like this

const { data: inventoryActivityResult, loading: inventoryActivityLoading, refetch: inventoryActivityFetch } = useQuery<{
  simulcastMyAccount: { data: any };
}>(RETRIEVE_BUYERACTIVITY, {
  variables: {
    apiKey: apiKey,
    list: 'Inventory',
  },
});

const { data: offersActivityResult, loading: offersActivityLoading, refetch: offersActivityFetch } = useQuery<{
  simulcastMyAccount: { data: any };
}>(RETRIEVE_BUYERACTIVITY, {
  variables: {
    apiKey: apiKey,
    list: 'Offers',
  },
});

const { data: bidsActivityResult, loading: bidsActivityLoading, refetch: bidsActivityFetch } = useQuery<{
  simulcastMyAccount: { data: any };
}>(RETRIEVE_BUYERACTIVITY, {
  variables: {
    apiKey: apiKey,
    list: 'Bids',
  },
});

I was wondering if there's a better way to do this. Is there a simple way to call all this queries without having to repeat the same code?

1
try using aliases - example below - Denis Tsoi

1 Answers

0
votes

Assuming that your query is the following

query simulcastMyAccount(
  list: String
  apiKey: String
) {
  simulcastMyAccount(
    apiKey: $apiKey
    list: $list
  ) {
    data
  }
}

You can restructure your query to leverage Aliases https://graphql.org/learn/queries/#aliases

(Since we know that list: Inventory/Offers/Bids are being used, we can insert them in the query rather than passing them as we variable.

example:

query getAllData($apiKey: String) {
  inventory: simulcastMyAccount(
    apiKey: $apiKey
    list: 'Inventory'
  ) {
    data
  }
  offers: simulcastMyAccount(
    apiKey: $apiKey
    list: 'Offers'
  ) {
    data
  }
  bids: simulcastMyAccount(
   apiKey: $apiKey
   list: 'Bids'
  ) {
    data
  }
}

Usage

const { 
  inventory: { 
    data: inventoryActivityResult, 
    loading: inventoryActivityLoading, 
    refetch: inventoryActivityFetch 
  }, 
  offers: {
    data: offersActivityResult, 
    loading: offersActivityLoading, 
    refetch: offersActivityFetch 
  },
  bids: {
    data: bidsActivityResult, 
    loading: bidsActivityLoading, 
    refetch: bidsActivityFetch
  }
} = useQuery<{
  getAllData: { data: any };
}>(RETRIEVE_BUYERACTIVITY, {
  variables: {
    apiKey: apiKey,
  },
});