Why does Apollo Client throw "Missing field" errors when calling writeQuery with incomplete data?

I’m using Apollo Client 3.4.x. When calling writeQuery and passing data that’s missing fields specified in the query, I would expect Apollo Client to just not care about those missing fields and leave them in the cache as-is, while updating the fields that are specified. In practice it does actually update the fields, but in development mode (if (__DEV__)) it also throws an error saying Missing field 'x' while writing result /* passed value(s), stringified */. The error is thrown here: https://github.com/apollographql/apollo-client/blob/b214dd1d31cdfe6b5477bb5887a7d9615a302b27/src/cache/inmemory/writeToStore.ts#L348-L363

Meanwhile, in the docs, under Editing existing data it says

If you include a field in query but don’t include a value for it in data , the field’s current cached value is preserved.

Am I misreading this? It reads to me like passing only the fields you want to write is completely supported behavior and shouldn’t be causing errors to be thrown, even if they are only thrown in development mode. At most it should be a warning with some kind of caveat like “if you only meant to update the data, you can safely ignore this warning”.

4 Likes

Did you managed to solve this ?

I ran into the same issue.
I have no workaround for using the writeQuery method. Instead, I use the updateQuery method if I need to partially overwrite a query.

Example:

const setThemeName = (name: ThemeNames): void => {
  cache.updateQuery({ query: Get_App_ThemeDocument }, (data) => ({
    appTheme: {
      __typename: "AppTheme",
      name: name,
      mode: data?.appTheme?.mode,
    },
  }));
};

data is the current data for this query in the cache, and you can then pass in the existing data on fields you do not want to overwrite.

1 Like

Any update on this???