【问题标题】:ApolloClient: How to synchronize Apollo cache after update on the server?ApolloClient:如何在服务器上更新后同步 Apollo 缓存?
【发布时间】:2019-09-11 11:17:25
【问题描述】:

我正在尝试在服务器上更新后同步 apollo 缓存。 我应该直接写入缓存还是只重新获取更新的数据?

我实际上是在尝试仅重新获取更新的数据,但仍然无法正常工作。

我有一个 programs(title: String) 查询,如果标题为空,则获取所有程序,请参见下面的代码:

class Programs extends React.Component {
  render() {
    const FIND_PROGRAMS = gql`query findPrograms($title: String) {
      programs(title: $title) {  id title description }
    }`

    return (
      // The query fetch all programs if title is empty
      <Query query={FIND_PROGRAMS} variables={{ title: '' }}> 
        {({ data, error, loading, refetch }) => {
          if (loading) return <span>Loading</span>
          if (error) return <span>{error.message}</span>

          return (
            <div>
              { data.programs.map(program => <ProgramSummary program={program} />)}

              <button
                onClick={() => axios
                  .patch('path/to/endpoint', payload)
                  .then(updatedProgram => {
                    // Should I update the cache myself with something like this ?
                    // client.writeData(...) 

                    // Or should I refetch only updated Program like this ?
                    refetch({ title: updatedProgram.title }) // Not working yet
                  })
                }
              >
                UpdateProgram
              </button>
            </div>
          )
        }}
      </Query>
    )
  }
}

我的重新获取不起作用,我应该做错了什么。 请帮忙。

【问题讨论】:

  • 它适用于refetch(),没有变量;

标签: javascript reactjs react-apollo apollo-client


【解决方案1】:

我认为无法正常工作的行为是由于您尝试更新特定对象(更新的数据)传递 GraphQL 对象数组(这是您的查询返回的内容,因此是您的刷新)。我的意思是,您不会要求某人更新某些东西,然后给他们一堆东西,您只需提供您想要更新的特定项目。

我建议使用突变来进行更新,使用它,您将按照文档所说的那样自动刷新数据,这或多或少是我之前所说的。

"[...] 如果您要更新单个项目,通常不需要更新函数,只要返回项目的 id 和更新的属性 [...]"。

见https://www.apollographql.com/docs/react/essentials/mutations#update。

希望我能帮到你。

【讨论】:

  • 我在 GraphQL 之外进行更新,使用简单的 REST 端点,更新可能来自其他用户。让我换个方式问。 refetch 函数似乎接受了一些与原始查询不同的变量。因此,应该可以根据新的变量值重新获取一组不同的数据。在这里,我只是想从初始结果中重新获取单个项目。我认为它仍在 API 规范中,但为什么它不起作用?
  • 访问您的项目会有很大帮助:)
猜你喜欢
  • 2021-05-09
  • 2020-05-11
  • 2021-07-14
  • 2019-11-26
  • 2020-05-09
  • 2021-03-24
  • 2019-04-02
  • 2021-10-20
  • 1970-01-01
相关资源
最近更新 更多