【问题标题】:Add to array in Apollo Client cache after create mutation创建突变后添加到 Apollo 客户端缓存中的数组
【发布时间】:2021-03-21 08:53:39
【问题描述】:

在通过突变创建项目后,尝试将项目自动添加到 Apollo 客户端中的缓存数组中,第 32 行出现 TypeScript 错误 (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>'

这是完整的代码

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],
      },
    })
  }
}

【问题讨论】:

    标签: typescript apollo apollo-client


    【解决方案1】:

    Typescript 抱怨 TQuery 可能有其他字段将被您的代码剥离。

    ...queryResult 添加到您的writeQuery 代码:

    cache.writeQuery<TQuery, TVariables>({
      query,
      variables,
      data: {
         ...queryResult,
        [fieldName]: [...queryResult[fieldName], newItem],
      },
    })
    

    【讨论】:

      猜你喜欢
      • 2020-11-27
      • 2020-02-03
      • 2020-02-03
      • 2021-10-06
      • 2017-03-18
      • 2019-02-17
      • 2017-09-06
      • 2020-06-07
      相关资源
      最近更新 更多