Arrays and Lists
So far we’ve only dealt with components that have a single instance of the components they’re composed from. For example, we’re only showing a single Newsfeed story, and within that story there’s just a single author with a single profile picture. Let’s look at how to handle more than one of something.
GraphQL includes support for arrays, which in GraphQL are called lists. A field can be not only a single scalar value but an array of them, or not only a single edge but an array of edges. The schema specifies whether each field is a list or not, but, oddly, the GraphQL query syntax doesn’t distinguish between selecting a singular field and selecting a list — a quirky exception to the design principle that a GraphQL response should have the same shape as the query.
Request:
query MyQuery {
viewer {
contacts { // List of edges
id // field on a single item
name
}
}
}
Response:
{
viewer: {
contacts: [ // array in response
{
id: "123",
name: "Chris",
},
{
id: "789",
name: "Sue",
}
]
}
}
As it happens, the schema in our example app has a topStories field that returns a list of Stories, as opposed to the topStory field we're currently using that returns just one.
To show multiple stories on our newsfeed, we just need to modify Newsfeed.tsx to use topStories.
Step 1 — Select a list in the fragment
Open Newsfeed.tsx and find NewsfeedQuery. Replace topStory with topStories, and run npm run relay.
const NewsfeedQuery = graphql`
query NewsfeedQuery {
topStories {
...StoryFragment
}
}
`;