Problem: Many times we have cases where we get data in list format from GraphQL query response. But in Relay when we want data from a fragment container we need to pass them as a single object.
Solution: Grpahql supports multiple directives for the rescue from side effects. In the same way, we can also create our own custom directives according to our needs.
Relay's team had created a custom hook for work around @relay(plural: true).
This directive indicates that relay's fragment container expects a prop of to be list of items instead of a single item.
Usage: A query or a parent with @relay(plural: true)
directive should have plural fields ie a field backed by GraphQl List
// Plural fragment definition
graphql`
fragment TodoItems_items on TodoItem @relay(plural: true) {
id
text
}
`;
// Plural fragment usage: note the parent type is a list of items (`TodoItem[]`)
fragment TodoApp_app on App {
items {
// parent type is a list here
...TodoItem_items
}
}
As described in the above example TodoItem's type is an array. So if you passed it without specifying given directive fragment won't execute.
But with the given directive we can get the desired output with an array.