Moti Bartov
Moti Bartov

Reputation: 3592

Flutter GraphQl client cache

I am using Flutter graphql_client which implemented pretty much as in this example

My client creation looks like this:

abstract class AbstractAdapter {
  Link get httpLink;

 GraphQLClient client;

 AbstractAdapter() {
   client = GraphQLClient(cache: InMemoryCache(), link: httpLink);
 }

 Future<QueryResult> query(QueryOptions options) {
   return client.query(options);
 }
}

It works pretty well but the problem is with the caching If I send the same mutation twice, it returns the cached result instead of sending it again!

Appreciates any help.

Upvotes: 5

Views: 4311

Answers (3)

Radhika Gokani
Radhika Gokani

Reputation: 178

You can either use FetchPolicy.networkOnly or updateCache after mutation is completed.

Upvotes: 0

Mostafa Dadkhah
Mostafa Dadkhah

Reputation: 71

you must use FetchPolicy.networkOnly in QueryOptions and MutationOptions , fetchPolicy property

      String query, Map<String, dynamic> variables) async {
    QueryOptions options = QueryOptions(
        documentNode: gql(query),
        variables: variables,
        fetchPolicy: FetchPolicy.networkOnly);

    final result = await _client.query(options);

    return result;
  }

Future<QueryResult> performMutation(
      String query, Map<String, dynamic> variables) async {
    MutationOptions options = MutationOptions(
        documentNode: gql(query),
        variables: variables,
        fetchPolicy: FetchPolicy.networkOnly);

    final result = await _client.mutate(options);
    return result;
  }

Upvotes: 5

Moti Bartov
Moti Bartov

Reputation: 3592

I've found the problem, I was trying to send mutation on a query api, this will return the last cached response which is not good for mutation.

I've added mutation query with MutationOptions to my GraphQL adapter like this:

abstract class AbstractAdapter {
Link get httpLink;

GraphQLClient client;

AbstractAdapter() {
  client = GraphQLClient(cache: InMemoryCache(), link: httpLink);
}

Future<QueryResult> query(QueryOptions options) {
  return client.query(options);
 }

Future<QueryResult> mutate(MutationOptions options) {
  return client.mutate(options);
 }
}

Upvotes: 1

Related Questions