Client Schema Extensions
note
See also the local data updates and client-only data sections of the guided tour.
Relay can be used to read and write local data, and act as a single source of truth for all data in your client application.
The Relay Compiler fully supports client-side extensions of the schema, which allows you to define local fields and types.
#
Table of Contents:#
Extending the server schemaTo extend the server schema, create a new .graphql
file inside your --src
directory.
Let's call it ./src/clientSchema.graphql
.
This schema describes what local data can be queried on the client. It can even be used to extend an existing server schema.
For example, we can create a new type called Note
:
And then extend the server schema type User
, with a list of Note
, called notes
.
#
Querying local stateAccessing local data is no different from querying your GraphQL server, although you are required to include at least one server field in the query.
The field can be from the server schema, or it can be schema agnostic, like an introspection field (e.g. __typename
).
Here, we use useLazyLoadQuery to get the current User
via the viewer
field, along with their id, name and the local list of notes.
#
Mutating local stateAll local data lives in the Relay Store.
Updating local state can be done with any updater
function.
The commitLocalUpdate
function is especially ideal for this, because writes to local state are usually executed outside of a mutation.
To build upon the previous example, let's try creating, updating and deleting a Note
from the list of notes
on User
.
#
CreateNote that since this record will be rendered by the ExampleQuery
via useLazyLoadQuery
, the query data will automatically be retained and won't be garbage collected.
If no component is rendering the local data and you want to manually retain it, you can do so by calling environment.retain()
:
#
Update#
Delete#
Initial local stateAll new client-side schema fields default to undefined
value. Often however, you will want to set the initial state before querying local data.
You can use an updater function via commitLocalUpdate
to prime local state.
Is this page useful?