

You can conditionally include or skip a field based on the value of a boolean variable. If you find yourself wanting to share inline fragments, it's likely a sign that it's time to refactor and introduce a new container. Note that it is highly recommended that Relay.Containers define their own fragments and avoid sharing inline var fragment = Relay.QL.
Graphql conditional fragment how to#
This schema information allows Relay to understand things like the types of field arguments, which fields are connections or lists, and how to efficiently refetch records from the server. Instead, these Relay.QL template expressions are transpiled into JavaScript descriptions via the babel-plugin-relay. To execute this code, Relay needs access to the schema - which can be too large to bundle inside the application. In this example, we want to query the primaryFunction on the hero field, but we can only query the primaryFunction field if the returned hero is a Droid type.Relay fragments, mutations, and queries must be specified using ES6 template literals tagged with Relay.QL. Whenever we want to query type-specific field s on an object with an abstract type, we have to use a type condition.

This comes in extremely handy when your rules rely on data from database. We can request that the server provides us the concrete type of the object by fetching the _typename metadata field. Fragments allow you to define which fields your rule requires to work correctly. In order to know if the type of an object in a response can be converted to another type, we have to know the concrete type of the object. In this case, that is either a Human or a Droid.

When we query the hero field, the server doesn't return a response object of the Character type, it returns either a concrete type that implements the Character interface. For example, if the variable in the following examples is truthy, then the name field will be included in the query response. Since it’s conditional, it makes sense to use a variable in the query to check for truthiness. hero ), the can be either a Human or a Droid. The include directive, true to its name, allows us to conditional include fields by passing an if argument. If you are querying a field that returns an interface or a union type, you will need to use inline fragments to access data on the underlying concrete type. That means the result of a field of the Character type (ie. Like many other type systems, GraphQL schemas include the ability to define interfaces and union types. In this example, we counted every field, no matter if it was on fragment definitions or if it was skipped. Since both the Human and Droid types implement the Character interface, they can both be converted into the abstract type Character. Field Arguments Errors Conditional Analysis.
