0

In attempting to automate adding an item to a cached array in Apollo Client after it's created via a mutation, there's a TypeScript error on line 32 (data: {):

Type '{ [x: string]: TFetchResultData[]; }' is not assignable to type 'TQuery'.
  '{ [x: string]: TFetchResultData[]; }' is assignable to the constraint of type 'TQuery', but 'TQuery' could be instantiated with a different subtype of constraint 'Record<string, TFetchResultData[]>'.ts(2322)
DataProxy.d.ts(17, 9): The expected type comes from property 'data' which is declared here on type 'WriteQueryOptions<TQuery, TVariables>'

Here's the full code

import { ApolloCache, DataProxy } from '@apollo/client'

export const addToArray = <
  TVariables,
  TData,
  TFetchResultData,
  TQuery extends Record<string, TFetchResultData[]>,
  K
>(
  cache: ApolloCache<K>,
  {
    query,
    variables,
    fieldName,
    newItem,
  }: {
    query: DataProxy.Query<TVariables, TData>['query']
    variables: DataProxy.Query<TVariables, TData>['variables']
    newItem: TFetchResultData
    fieldName: keyof TQuery
  }
): void => {
  // Add to the documentFiles field, if it exists
  const queryResult = cache.readQuery<TQuery, TVariables>({
    query,
    variables,
  })
  if (queryResult) {
    cache.writeQuery<TQuery, TVariables>({
      query,
      variables,
      data: {
        [fieldName]: [...queryResult[fieldName], newItem],
      },
    })
  }
}

1 Answer 1

1
+100

Typescript is complaining that TQuery might have additional fields that will be stripped by your code.

Add ...queryResult to your writeQuery code:

cache.writeQuery<TQuery, TVariables>({
  query,
  variables,
  data: {
     ...queryResult,
    [fieldName]: [...queryResult[fieldName], newItem],
  },
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.