Как сохранить синхронизацию данных в ember с помощью ember-apollo-client? - PullRequest
0 голосов
/ 07 февраля 2019

У меня есть приложение, созданное с использованием Ember и ember-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 Data с ember-graphql-адаптер ИЛИ просто ember-apollo-client.Я продолжил с apollo из-за его лучшей документации.

Не думаю, что понял, как это сделать.Должен ли я как-то использовать store в сочетании с watchQuery из apollo?Или это что-то еще?

ПОСЛЕДНЕЕ РЕДАКТИРОВАНИЕ

Ади почти прибил его.

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

1 Ответ

0 голосов
/ 07 февраля 2019

Вы можете использовать API императивного магазина apollo, подобный этому:

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