apollo-feature-requests icon indicating copy to clipboard operation
apollo-feature-requests copied to clipboard

ApolloClient: Allow Cache FieldPolicy 'read' functions to be asynchronous .

Open adorsk opened this issue 5 years ago • 0 comments

Problem Description

FieldPolicy 'read' functions can not be asynchronous (I think?).

For example, if I write something like the snippet below, a query that uses the field todos as a @client field does not resolve correctly. The 'loading' attribute of the queryResult does change from false to true, but the data attribute does not contain the argument passed to resolve.

export const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        todos: {
          async read () {
            return new Promise((resolve) => {
              setTimeout(() => {
                const todos = todosVar();
                resolve(todos);
              });
            });
          }
        },
      }
    }
  }
});

What I'd like is to use an asynchronous read function.

Possible Use Cases

  1. Ability to use async sources in read functions. For example, a Dexie DB or an external API.

  2. Ability to simulate async behavior of a remote source. For example, when mocking an app w/out a backend, it would be useful to simulate async loading. This is similar to the 'virtual fields' concept in (the documentation)[https://www.apollographql.com/docs/tutorial/local-state/#query-local-data], which are currently implemented via local resolvers.

Possible Solution

Allow for asynchronous read functions. Easy for me to write, I imagine a bit harder to implement ;)

adorsk avatar Sep 10 '20 14:09 adorsk