2

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

3
  • Please be more specific than "this doesn't work". Are you seeing any errors in the console? What's the expected behavior and what unexpected behavior are you actually seeing when your code runs? Commented Mar 7, 2019 at 15:08
  • It may also be helpful to see how you're querying this client state and what your apollo client config is, since these are both factors that can contribute to something "not working" Commented Mar 7, 2019 at 15:10
  • I have updated the readQuery part. This is very simple write to the cache. I just wanted to add some defaults to the app in cache to check if I can later push my app state from this.state={} to apollo cache Commented Mar 7, 2019 at 15:36

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot man. I had the '__typename' inside the data for the whole object but didn't have '__typename' for individual nested objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.