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

本文是小编为大家收集整理的关于将嵌套对象写入Apollo客户端缓存中的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我试图将嵌套对象写入阿波罗缓存,但它不起作用.简单的变量写入正常工作.我正在使用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的本文地址:https://www.itbaoku.cn/post/1938083.html

问题描述

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

推荐答案

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.