Joey Yi Zhao
Joey Yi Zhao

Reputation: 42416

How can I use `schema` in apollo client cache?

I use apollo-client in a react project to manage UI state. I define a schema type for apollo mutation but it doesn't seem to work.

Below is how I create apollo client instance.

const cache = new InMemoryCache();

export const createClient = () => {
  return new ApolloClient({
    cache,
    resolvers: {
      Mutation: {
        ...alertResolvers
      },
    },
    typeDefs: [alertTypeDefs]
  });
};

Below code is the type schema definition. As you can see I have created a showErrorAlert return type of Alert.

export const alertTypeDefs = gql`
  type Alert {
    id: ID!
    message: String!
    type: String!
    duration: Int!
  }
  extend type Mutation {
    showErrorAlert(message: String!): Alert
  }
`;

I use below code to send mutation. As you can see that it doesn't return the duration in the return object. But the application works without any error. It seems that the type doesn't have impact on the application.

gql`
  mutation showErrorAlert($message: String!) {
    showErrorAlert(message: $message)  @client {
      id
      message
      type
    }
  }
`;

Upvotes: 1

Views: 504

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84657

From the docs:

You can optionally set a client-side schema to be used with Apollo Client, through either the ApolloClient constructor typeDefs parameter, or the local state API setTypeDefs method... This schema is not used for validation like it is on the server because the graphql-js modules for schema validation would dramatically increase your bundle size. Instead, your client-side schema is used for introspection in Apollo Client Devtools, where you can explore your schema in GraphiQL.

In other words, the only point of providing typeDefs for local state is enable querying local state through GraphiQL in Apollo Client Devtools.

There is no type validation for local state, although the client will throw if there is a mismatch in the general shape of the object in the cache compared to what's being requested.

Upvotes: 1

Related Questions