将嵌套对象写入 Apollo 客户端缓存
Writing nested object to Apollo client cache
我正在尝试将嵌套对象写入 apollo 缓存,但它不起作用。简单的变量写入工作正常。我正在使用 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
字段来解决它。例如:
client.writeData({
data: {
name: 'mr x',
address: {
id: 1,
country: 'y',
city: 'z',
__typename: "Address"
},
age: 25
}
})
我还要补充一点,包含一个 'id' 字段是个好主意(除非您配置了 getIdFromObject
选项)。在 Apollo 的 Cache Normalization section.
中有更多信息
作为参考,我得到的错误是:
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 缓存,但它不起作用。简单的变量写入工作正常。我正在使用 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
字段来解决它。例如:
client.writeData({
data: {
name: 'mr x',
address: {
id: 1,
country: 'y',
city: 'z',
__typename: "Address"
},
age: 25
}
})
我还要补充一点,包含一个 'id' 字段是个好主意(除非您配置了 getIdFromObject
选项)。在 Apollo 的 Cache Normalization section.
作为参考,我得到的错误是:
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.