Writing nested object to Apollo client cache

你。 提交于 2020-02-04 04:05:04

问题


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

回答1:


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

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:

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.



来源:https://stackoverflow.com/questions/55046690/writing-nested-object-to-apollo-client-cache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!