Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Interacting with cached data


The ApolloClient object provides the following methods for interacting with cached data:

  • readQuery
  • readFragment
  • writeQuery
  • writeFragment

These methods are described in detail below.

Important: You should call these methods on your app's ApolloClient object, not directly on the cache. By doing so, the ApolloClient object broadcasts cache changes to your entire app, which enables automatic UI updates. If you call these methods directly on the cache instead, changes are not broadcast.

All code samples below assume that you have initialized an instance of ApolloClient and that you have imported the gql tag from graphql-tag.

readQuery

The readQuery method enables you to run GraphQL queries directly on your cache.

If your cache contains all of the data necessary to fulfill a specified query, readQuery returns a data object in the shape of your query, just like a GraphQL server does.

If your cache doesn't contain all of the data necessary to fulfill a specified query, readQuery throws an error. It never attempts to fetch data from a remote server.

Pass readQuery a GraphQL query string like so:

const { todo } = client.readQuery({
  query: gql`
    query ReadTodo {
      todo(id: 5) {
        id
        text
        completed
      }
    }
  `,
});

You can provide GraphQL variables to readQuery like so:

const { todo } = client.readQuery({
  query: gql`
    query ReadTodo($id: Int!) {
      todo(id: $id) {
        id
        text
        completed
      }
    }
  `,
  variables: {
    id: 5,
  },
});

Do not modify the return value of readQuery. The same object might be returned to multiple components. To update data in the cache, instead create a replacement object and pass it to writeQuery.

readFragment

The readFragment method enables you to read data from any normalized cache object that was stored as part of any query result. Unlike readQuery, calls to readFragment do not need to conform to the structure of one of your data graph's supported queries.

Here's an example:

const todo = client.readFragment({
  id: ..., // `id` is any id that could be returned by `dataIdFromObject`.
  fragment: gql`
    fragment myTodo on Todo {
      id
      text
      completed
    }
  `,
});

The first argument, id, is the unique identifier that was assigned to the object you want to read from the cache. This should match the value that your dataIdFromObject function assigned to the object when it was stored.

For example, let's say you initialize ApolloClient like so:

const client = new ApolloClient({
  ...,
  cache: new InMemoryCache({
    ...,
    dataIdFromObject: object => object.id,
  }),
});

If a previously executed query cached a Todo object with an id of 5, you can read that object from your cache with the following readFragment call:

const todo = client.readFragment({
  id: '5',
  fragment: gql`
    fragment myTodo on Todo {
      id
      text
      completed
    }
  `,
});

In the example above, if a Todo object with an id of 5 is not in the cache, readFragment returns null. If the Todo object is in the cache but it's missing either a text or completed field, readFragment throws an error.

writeQuery and writeFragment

In addition to reading arbitrary data from the Apollo Client cache, you can write arbitrary data to the cache with the writeQuery and writeFragment methods.

Any changes you make to cached data with writeQuery and writeFragment are not pushed to your GraphQL server. If you reload your environment, these changes will disappear.

These methods have the same signature as their read counterparts, except they require an additional data variable.

For example, the following call to writeFragment locally updates the completed flag for a Todo object with an id of 5:

client.writeFragment({
  id: '5',
  fragment: gql`
    fragment myTodo on Todo {
      completed
    }
  `,
  data: {
    completed: true,
  },
});

All subscribers to the Apollo Client cache see this change and update your application's UI accordingly.

As another example, you can combine readQuery and writeQuery to add a new Todo item to your cached to-do list:


const query = gql`
  query MyTodoAppQuery {
    todos {
      id
      text
      completed
    }
  }
`;

// Get the current to-do list
const data = client.readQuery({ query });

const myNewTodo = {
  id: '6',
  text: 'Start using Apollo Client.',
  completed: false,
  __typename: 'Todo',
};

// Write back to the to-do list and include the new item
client.writeQuery({
  query,
  data: {
    todos: [...data.todos, myNewTodo],
  },
});

Previous: Configuring the cache
Next: Using Apollo with TypeScript