首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何保持数据同步在成员使用成员-阿波罗-客户端?

如何保持数据同步在成员使用成员-阿波罗-客户端?
EN

Stack Overflow用户
提问于 2019-02-07 14:08:26
回答 1查看 290关注 0票数 0

我有一个使用Ember余烬-阿波罗-客户构建的应用程序。

代码语言:javascript
复制
// templates/collaborators.hbs

// opens an ember-bootstrap modal
{{#bs-button type="success" onClick=(action (mut createCollaborator) true)}}Create collaborator{{/bs-button}}
// submit button in modal triggers "createCollaborator" in controller    

{{#each model.collaborators as |collaborator|}}
    {{collaborator.firstName}} {{collaborator.lastName}}
{{/each}}
代码语言:javascript
复制
// routes/collaborators.js
import Route from '@ember/routing/route';
import { RouteQueryManager } from 'ember-apollo-client';
import query from '../gql/collaborators/queries/listing';

export default Route.extend(RouteQueryManager, {
    model() {
        return this.get('apollo').watchQuery({ query }); 
    }
});

// controllers/collaborator.js
export default Controller.extend({
  apollo: service(),

  actions: {
    createCollaborator() {
      let variables = { 
        firstName: this.firstName, 
        lastName: this.lastName, 
        hireDate: this.hireDate 
      }

      return this.get('apollo').mutate({ mutation, variables }, 'createCollaborator')
        .then(() => {
          this.set('firstName', '');
          this.set('lastName', '');
          this.set('hireDate', '');
      });
    }
  }
});

当前,在创建协作程序之后,数据已经过时,需要进行浏览器刷新才能更新。我希望这些更改能够立即在协作者列表中显示出来。

据我所知,为了在Ember中使用GraphQL,我应该使用Ember Data适配器,或者使用ember-apollo-client。我继续使用apollo,因为它有更好的文档。

我想我不太懂怎么做。我是否应该以某种方式使用store与来自apollowatchQuery相结合?或者是别的什么东西?

稍后编辑

Adi差一点就搞定了。

  • mutationResult实际上需要突变本身。
  • store.writeQuery中的第二个param应该是data: { cachedData }data,如下所示。

把这个留在这里,因为它可能会帮助到其他人。

代码语言:javascript
复制
return this.get('apollo').mutate({
    mutation: createCollaborator,
    variables,
    update: (store, { data: { createCollaborator } }) => {
      const data = store.readQuery({ query })

      data.collaborators.push(createCollaborator);

      store.writeQuery({ query, data });
    }
  }, createCollaborator');
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-07 14:39:55

您可以使用类似于以下内容的阿波罗命令式存储API:

代码语言:javascript
复制
return this.get('apollo').mutate(
    { 
        mutation, 
        variables, 
        update: (store, { data: {mutationResult} }) => {
            const cachedData = store.readyQuery({query: allCollaborators})

            const newCollaborator = mutationResult; //this is the result of your mutation

            store.writeQuery({query: allCollaborators, cachedData.push(newCollaborator)})
        }
    }, 'createCollaborator')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54575212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档