代码之家  ›  专栏  ›  技术社区  ›  acmoune

Apollo客户端:在服务器上更新后如何同步Apollo缓存?

  •  0
  • acmoune  · 技术社区  · 7 年前

    我正在尝试在服务器上更新后同步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>
        )
      }
    }
    

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

    0 回复  |  直到 7 年前
        1
  •  0
  •   Henry Vanner Aquino Vegas    7 年前

    我认为不起作用的行为是由于您试图更新一个特定的对象(更新的数据),并通过GraphQL传递一个对象数组(这是您的查询返回的结果,因此也是您的刷新结果)。我的意思是,你不会要求别人更新一些东西,然后给他们一堆东西,你只需要给你想要更新的特定物品。

    我建议改为使用变异来进行更新,这样你的数据就会像文档中说的那样自动刷新,这和我之前说的差不多。

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

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

    希望我帮了你。

    推荐文章