React Native
Relay (GraphQL)
Getting Started
18 min
get started with graphql relay introduction in this guide you will learn what is relay, how to work with schema and understand how to work with graphql on back4app prerequisites this is not a tutorial yet, but to feel free confortable reading it you will need basic javascript knowledge basic understand about graphql if you don’t have, the graphql js its a perfect place to start relay relay is a graphql client developed by facebook engineering team and designed for performance when building data driven applications more precisely, relay is a framework for declaratively fetching and managing graphql data on the client side that uses strict conventions to help your application succeed it was built with scalability in mind to power complex applications like facebook the ultimate goal of graphql and relay is to deliver instant ui response interactions one of the main advantages of using graphql is that you can fetch with a single query all the data needed to build an application page, for example off course that this is good(you can save round trips to the server) but with that comes a problem you may use different queries to the same component when reusing this component in different parts of your application to avoid this kind of problem relay uses an important concept colocation colocation when using relay, components and their data requirements live together components data requirements are declared inside them that means all the components declare the data that they need relay ensures that each component has the data it needs when renders the relay structure behind the colocation concept are the containers the most common is the relay fragment container the container is the component that attempts to fulfill the data required when rendering each component the containers declare their data dependency using graphql fragments every component will have its own fragment container the container doesn’t fetch the data directly; it only declares the specification for the data needed when rendering the data will be fetched on the server side relay will make sure that the data is available before the rendering occurs relay composes a tree of data with those containers, ignoring the redundancies, and fetching the data on the server let’s illustrate the concept with an example a fragment is a selection of fields on a graphql type relay works with fragment, pagination and refetch container the most common is a fragment container see below a fragment in graphql and after the same on relay 1 query health { 2 health 3 } 1 type homeprops = { 2 query home query; 3 }; 4	 5 const home = ({query} homeprops) => { 6 return ( 7 \<view> 8 \<text>api health {query health ? 'health' 'not health' }\</text> 9 \</view> 10 ); 11 }; 12	 13 const homefragment = createfragmentcontainer(home, { 14 query graphql` 15 fragment home query on query { 16 health 17 } 18 `, 19 }); 20	 21 export default createqueryrenderermodern(homefragment, home, { 22 query graphql` 23 query homequery { 24 home query 25 } 26 `, 27 hidesplash true, 28 }); on the first code you can see the graphql version that allows us to split this query into reusable fragments on the next code you can see the relay one that is showing the fragments and the data together in the same component colocation means that data definitions and view definitions live together collocation has some benefits we just need to declare exactly the date that we need that means it is hard to over fetch data which improves our application and is hard to under fetch data which prevent errors with missing data another important concept is data masking which means that components can only access data they asked for data masking helps to prevent dependency errors also, components are only updated if the data they are using change query renderer modern we recommend to take a look at the official query renderer docs https //relay dev/docs/en/query renderer html#docsnav for a better understanding based on the fragment containers, relay will read them and make the request to the server based on the data they have but, how does this requisition happen? this is where query renderer modern comes in the query renderer modern is the component that reads the fragment containers, makes the request to the server and returns the data to the component every root component will have a query renderer modern making this request in the example above what we have an abstraction so that we pass only the fragment that must be read and so all the rest of the work is done inside createqueryrenderermodern in the next step of the doc we will enter the createqueryrenderermodern to understand the abstraction based on the pure example above below is a pure example of query render modern 1 export default function artistrenderer({artistid}) { 2 return ( 3 \<queryrenderer 4 environment={environment} 5 query={graphql` 6 query queryrenderersartistquery($artistid string!) { 7 # the root field for the query 8 artist(id $artistid) { 9 # a reference to your fragment container 10 artistheader artist 11 } 12 } 13 `} 14 variables={ {artistid} } 15 render={({error, props}) => { 16 if (error) { 17 return \<div>{error message}\</div>; 18 } else if (props) { 19 return \<artist artist={props artist} />; 20 } 21 return \<div>loading\</div>; 22 }} 23 /> 24 ); 25 } we can see that the query renderer modern is a hoc component in other words, wrap the component that owns the container with the data to be requested, make the request with the relay environment and return the data downwards passing to the component automatic type generation working with relay we can build an application type safely as we said every component will be the owner of their data so, when we run the relay compiler, it reads every fragment of data and makes a check with your graphql schema if all checks of relay compiler is ok, the types it will be generate in a folder called generated this folder is create inside of the root components folders see the example below component home checking the api health 1 const home = ({query} homeprops) => { 2 return ( 3 \<view> 4 \<text>api health {query health ? 'health' 'not health' }\</text> 5 \</view> 6 ); 7 }; 8	 9 const homefragment = createfragmentcontainer(home, { 10 query graphql` 11 fragment home query on query { 12 health 13 } 14 `, 15 }); 16	 17 export default createqueryrenderermodern(homefragment, home, { 18 query graphql` 19 query homequery { 20 home query 21 } 22 `, 23 hidesplash true, 24 }); generated folder containing the types for home component and the types generated after this we just need import the type on component and compose it 1 import {home query} from " / generated /home query graphql"; 2 3 type homeprops = { 4 query home query; 5 }; the type is generate in flow, the core language for types from facebook but, with a library you can generate in typescript this is most common to work with react native resuming, with relay compiler we can check the data implementation before run time this helps us to prevent bugs and then improve the application quality and development time on queries, we can avoid duplicate data in n different components it check if some data is duplicate if has it will remove the redundancies this will reduce the payload size of queries and increase the performance of application even more developing on queries, we can avoid duplicate data in n different components it check if some data is duplicate if has it will remove the redundancies this will reduce the payload size of queries and increase the performance of application even more on the server side back4app back4app generates a ready to use relay compliant graphql api to use on your project what back4app generates for you so you don’t have to build by yourself on server side infrastructure on back4app dashboard you can create a complete data model with classes, types and everything else a database needs you don’t have to worry about setup and maintain server by yourself after create your data model back4app we will generate everything that is necessary to consume it on the frontend side using graphql let’s take a look at the graphql api schema schema the schema file is the core of any graphql application it describes the whole server available to be use on client side relay works using your schema file to confirm the queries string and generated file to appear in / generated /mycomponent graphql, as we said on automatic type generation topic to use the relay compiler, you need either a graphql or json graphql schema file describing your graphql server’s api these files are local representations of a server source of truth and are not edited every schema of graphql can be compose by query type, mutation type and subscription type to work with a schema being consume by relay on front end, you need some of core concepts on back end node interface and connection we recommend reading about node interface and relay connections to turn this reading more easier to abstract node interfaces the node interface implements every type on graphql to help fetch data via id this is an implementation to make more easy fetch data from server and updated so each data of each type it will have a unique id, called as global unique id, being implemented by a node interface with node, relay avoid nested queries and make the fetch and re fetch using it this is hard to implement and needs a bit of work, but we already build this for you! pagination build to be compose, as on front end on back end the relay it will help us to compose our data to for work with pagination we have connections those connections implements the node from the type we are fetching and have a standard model, facilitating the implementation of pagination on server side fortunately, again, we have this already build to use on frontend conclusion in this guide we introduced what is relay, its main concepts and how it works also we could see how back4app automates the graphql server creation and delivers us a complete database with graphql api to work with resuming, the whole backend is already built by back4app you only need to create your types on the dashboard and start to consume based on schema generated in the next section we will explain how to handle this schema on the front end and how to prepare your environment to use relay we also have a graphql cookbook https //www back4app com/docs/parse graphql/graphql getting started , you can use it to help you to understand more concepts on our dashboard