将嵌套对象写入 Apollo 客户端缓存 [英] Writing nested object to Apollo client cache

查看:41
本文介绍了将嵌套对象写入 Apollo 客户端缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将嵌套对象写入 apollo 缓存,但它不起作用.简单的变量写入工作正常.我正在使用 Apollo-client v2.4

I am trying to write a nested object to apollo cache but it it not working. Simple variables writes are working fine. I am using Apollo-client v2.4

// Schema
const GET_DATA_FROM_CACHE = gql `
  name
  address
  age
`
// Reading data from cache
  render() {
    return (
    <Query query = {GET_DATA_FROM_CACHE} fetchPolicy = {"cache-only"}>
      {({ data }) => (
        <View >
          <Text> Name: {data.name} </Text>
        </View>
      )}
    </Query>
   )
  }

// THIS WORKS as I can see the name in my Text field

client.writeData({
  data: {
    name: 'mr x',
    age: 25
  }
})

// THROWS ERROR: "cannot read property country of undefined"

client.writeData({
  data: {
    name: 'mr x',
    address: {
      country: 'y',
      city: 'z'
    },
    age: 25
  }
})

推荐答案

我遇到了这个问题,并通过确保在嵌套对象中包含一个具有适当值的 __typename 字段来解决它.例如:

I was running into this issue and resolved it by ensuring I included a __typename field with the appropriate value in the nested object. For example:

client.writeData({
  data: {
    name: 'mr x',
    address: {
      id: 1,
      country: 'y',
      city: 'z',
      __typename: "Address"
    },
    age: 25
  }
})

我还要补充一点,包含一个id"字段是个好主意(除非您已经配置了 getIdFromObject 选项).Apollo 的缓存规范化部分中有更多信息.

I would also add that it is a good idea to include an 'id' field (unless you've configured the getIdFromObject option). There's more info in Apollo's Cache Normalization section.

作为参考,我得到的错误是:

For reference, the error I was getting was:

不变违规:存储错误:应用程序试图写入一个没有提供 id 但商店已经包含一个 id 的对象{Typename}:此对象的{id}.

Invariant Violation: Store error: the application attempted to write an object with no provided id but the store already contains an id of {Typename}:{id} for this object.

这篇关于将嵌套对象写入 Apollo 客户端缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆