11. The @client directive
2m

Directive: A GraphQL directive is like a special instruction for part of your GraphQL schema or operation.

The @client directive

To use the @client directive, add @client after the name of the field in your query.

The client directive syntax
Example of how to use the @client directive
query GetTrack($trackId: ID!) {
track(id: $trackId) {
title
thumbnail
length
# ... other fields
numberOfLikes @client
}
}

How does it work?

  1. The @client directive tells Apollo Client that the field is a local-only field.
  2. Apollo Client will then omit that field from the query it sends to the GraphQL server.
  3. Instead, Apollo Client will check the field policy (which we'll set up later) to fulfill the field.
What happens when you add the client directive

Code-along: Using the @client directive

Goal: Query the numberOfLikes field using the @client directive

  1. Open up the src/pages/track-details-page.js file and find the GET_TRACK_DETAILS query.

    const GET_TRACK_DETAILS = gql`
    query GetTrackDetails($trackId: ID!) {
    track(id: $trackId) {
    id
    title
    author {
    id
    name
    photo
    }
    thumbnail
    length
    modulesCount
    numberOfViews
    modules {
    id
    title
    length
    }
    description
    }
    }
    `;
  2. Add the numberOfLikes field to the query. Where you add it doesn't really matter, but we've decided to add it after the numberOfViews field.

    After the field, add the @client directive.

    const GET_TRACK_DETAILS = gql`
    query GetTrackDetails($trackId: ID!) {
    track(id: $trackId) {
    id
    title
    author {
    id
    name
    photo
    }
    thumbnail
    length
    modulesCount
    numberOfViews
    numberOfLikes @client
    modules {
    id
    title
    length
    }
    description
    }
    }
    `;

Check your work

Though we won't see anything change in the browser, we can check if the directive is working.

Open up the Network tab in your browser. Click on a track from the homepage and look for the request to the GraphQL API.

From the payload request, you can check the query we sent and confirm that we did not send a numberOfLikes field.

Previous
Next