首页 > 解决方案 > 存储错误:应用程序试图写入一个没有提供类型名的对象,但存储已经包含一个对象

问题描述

在我更新缓存时发生突变后,更改会反映在 UI 中,但出现以下错误

不变违规:存储错误:应用程序尝试写入一个没有提供类型名称的对象,但存储已经包含一个类型名称为 ItemCodeConnection 的对象,用于 id $ROOT_QUERY.itemCodes({"filter":{"number":10000001} })。试图写入的 selectionSet 是: {"kind":"Field","name":{"kind":"Name","value":"itemCodes"},"arguments":[{"kind" :"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"Variable","name":{"kind":" Name","value":"filter"}}}],"directives":[],"selectionSet":{"kind":"SelectionSet","

GraphQL 查询:

const CREATE_ITEM_CODE_SPEC = gql`
mutation createItemCodeSpec($input: createItemCodeSpecInput) {
    createItemCodeSpecification(input: $input){
        __typename
        id
        itemCode {
            number
        }
        product
        spec_class
        grade
    }
}
`

const GET_ITEM_CODE  = gql`
    query itemCode($filter: filterInput){
        itemCodes(filter: $filter){
            itemCodes {
                number
                type
                description
                group 
                item_code_spec {
                    id
                    itemCode {
                        number
                    }
                product
                spec_class
                grade
           }
             created_on
             created_by
             changed_on
             changed_by      
            }
        }
    }
`

下面是突变:

const [mutation, { data, loading, error}] = useMutation(
        CREATE_ITEM_CODE_SPEC,
        {
            update(cache, { data: { createItemCodeSpecification } }){
                const currentData  = cache.readQuery({
                    query: GET_ITEM_CODE,
                    variables: { filter : {number:itemCode} } 
                })
                cache.writeQuery({
                    query: GET_ITEM_CODE,
                    variables: { filter : {number:itemCode} },
                    data: {
                        ...currentData,
                        itemCodes: {
                            itemCodes: currentData.itemCodes.itemCodes.map((itemCode, index) => {
                                return {
                                    ...itemCode,
                                    item_code_spec: index === 0? [
                                        ...itemCode.item_code_spec,
                                        createItemCodeSpecification
                                     ] : itemCode.item_code_spec
                                }
                            })
                        }
                    }
                }) 
            }
        }
        );

标签: graphqlapolloapollo-client

解决方案


您只需为查询的每个子部分添加“id”。在 GET_ITEM_CODE 查询中为“itemCodes”添加“id”可能会解决您的问题。


推荐阅读