4IT580: Docs
4IT580 WebGitLab

6th Practical Class:
GraphQL on FrontEnd

App Setup

GraphQL Code Generation

We are using GraphQL Code Generator to generate TypeScript types from GraphQL queries.

  1. Download GraphQL schema from backend to frontend:
  1. Generate TypeScript from GraphQL queries and watch for file changes on frontend:

Apollo Client

❗Quacker and team projects use v3, while the latest version is v4.

Apollo Provider

The component wraps the React app and places Apollo Client on the context, enabling you to access it from anywhere in your component tree.

Minimal setup:

Hook

query: A request for specific data from a GraphQL server. Clients define the structure of the response, enabling precise and efficient data retrieval.


API

The variable must use the following syntax to recognized by the GraphQL Code Generator.

Pay special attention to the magic comment and the placement of the backticks!

Example

Hook

mutation: A GraphQL operation that modifies data on the server. It allows clients to perform create, update, or delete operations, altering the underlying data.


API

Example

Fragments

fragment: A selection set of fields that can be shared between multiple query operations.

Example

Fragments in frontend code

Step 1 - Define a fragment

Fragment name (e.g. ) has to be unique!

File:

Step 2 - Use fragment in a GraphQL query/mutation/fragment

When we try to access the data from the fragment directly in the component, TypeScript will complain. But that's a good thing! The component should not be coupled with the fragment data which is only a dependency required by the component.

File:

Step 3 - Get fragment data in children

Use the function from GraphQL Codegen to "reveal" the data from the fragment.

It is not a React hook - think of it more as a helper function to get the fragment data.

❗Import from . If you import it from , it will not work.


Summary

Fragment masking helps express data dependencies of components with GraphQL fragments.

By doing so, we ensure that the data is properly passed down to the components without "leaking" to parent components. It also allows to colocate the Fragment definitions with their components.

More about GraphQL Fragment Masking

and

and are generic types that can create TypeScript types from GraphQL queries.