将嵌套对象写入Apollo客户端缓存 [英] Writing nested object to Apollo client cache
问题描述
我正在尝试将嵌套对象写入阿波罗缓存,但是它不起作用.简单的变量写工作正常.我正在使用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屋!