Velidan
Velidan

Reputation: 6019

How to fetch an array as result in Apollo?

Let's imagine we have such schema on our server with a query that simply fetches a list of Topics based on the passed name argument.

Query listTopics(
name: String!
): [Topic!]!

type Topic {
id: String!
name: String!
image: String
timeBasedFeed: String!
scoreBasedFeed: String!
aliases: [String!]!
parents: [String!]!
allAncestors: [String!]!
}

How can we declare that the query returns an array on the client while we fetching the data?

When we work with a query that returns an object, etc. we can do next thing

import { gql, useQuery } from '@apollo/client';

const GET_DOG = gql`
  query GetDog { 
      // Declare response fields
      id
      name
     }
`;

But how to do the same when the query returns an array?

I tried to do it in this way

import { gql } from '@apollo/client';

export const LIST_TOPICS_QUERY = gql`
  query listTopics($name: String!) {
      [ 
        id,
        name,
        image,
        timeBasedFeed,
        storeBasedFeed,
        aliases,
        parents,
        allAncestors
      ]
  }
`;

It doesn't work, unfortunately.

Thanks for any info.

Upvotes: 1

Views: 3133

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84657

There's no difference in how you specify the selection set for a field that returns a single object and a field that returns a list of objects -- the syntax is identical, even though the shape of the response will be different.

Upvotes: 3

Related Questions