timhall / svelte-apollo

Svelte integration for Apollo GraphQL
MIT License
947 stars 68 forks source link

Expose `setVariables` of ObservableQuery #49

Closed peacememories closed 3 years ago

peacememories commented 4 years ago

Hi, I've been using svelte-apollo for a few days now. I just ran into the following issue:

I have a sapper page where I change the url without leaving the current route, meaning that the component continues to live and the results of preload just get updated in the props. In my case the cache variable as explained in the examples here. To actually make use of the new data I have wrapped my cache writing logic in a reactive block, like so:

$: {
    client.writeQuery({
      query: FEATURE_GROUP,
      variables: { id: cache.data.featureGroup.id },
      data: cache.data
    });
  }

I am using client.writeQuery instead of restore, because I need to supply variables to the restored query which does not seem to work at least in the latest npm version of svelte-apollo.

Now when I actually change the url, the cache gets updated, but nothing else happens. This is because the query, while it's technically supposed to react to cache changes, is still using the old id variable. To change this, I would either have to reconstruct a query every time, or use refetch. Using refetch has the problem that the cache never gets hit, so I have unnecessary fetches every time I navigate. Reconstructing the query is also slightly awkward because I have a derived reactive object that depends on the query and would also need to be recreated, also I don't have a neat version to not do all this on the first load, so I would always create my objects twice.

I think what I would really need is access to the setVariables function of the ObservableQuery from apollo.