【问题标题】:How to keep data synchronized in ember using ember-apollo-client?如何使用 ember-apollo-client 在 ember 中保持数据同步?
【发布时间】:2019-02-08 23:54:35
【问题描述】:

我有一个使用 Emberember-apollo-client 构建的应用。

// 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}}
// 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', '');
      });
    }
  }
});

目前,在创建协作者后,数据已过时,需要刷新浏览器才能更新。我希望立即在协作者列表中看到更改。

据我了解,为了将 GraphQL 与 Ember 一起使用,我应该将 Ember Dataember-graphql-adapter 一起使用,或者只使用 ember-apollo-client。我继续使用apollo,因为它有更好的文档。

我认为我不太了解如何做到这一点。我应该以某种方式将storeapollo 中的watchQuery 结合使用吗?还是别的什么?

稍后编辑

Adi 几乎成功了。

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

将其留在这里,因为它可能对其他人有所帮助。

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');

【问题讨论】:

    标签: javascript ember.js handlebars.js graphql apollo


    【解决方案1】:

    您可以使用类似这样的 apollo 命令式存储 API:

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

    【讨论】:

      猜你喜欢
      • 2019-10-26
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多