mercredi 10 février 2016

How to update Ember Data after create using JSONAPI?

I'm not sure what I'm missing here but after sending a save() request to the API, I'm finding that the list within the template is not updating.

I'm using the JSONAPI adapter, and after the create has been completed, it returns a corresponding post-create payload response containing all the new information, which I can see is in fact updating the note model in the Ember Inspector correctly with the information from the payload.

I've also tried to add in lines like:

get(this, 'notes').pushObject(note);

and alternatively:

get(this, 'notes').addObject(note._internalModel);

which I found from SO and Ember Forums, but they both return a warning:

The result of a server query (on testapp@model:note:) is immutable.

From what I've read I thought the JSONAPI adapter should be handling this (which it looks like it is from within Ember Inspector) but I just can't see any changes reflected in the template.

I have the following:

route.js

import Ember from 'ember';

export default Ember.Route.extend({
    model(params) {

        return Ember.RSVP.hash({
            contact:    this.store.findRecord('contact', params.contact_id),
            notes:      this.store.query('note', {filter: {contact_id: params.contact_id}}),
            note:       this.store.createRecord('note'),
        });
    },

    setupController(controller, model) {
        controller.set('contact', model.contact);
        controller.set('notes', model.notes);
        controller.set('note', model.note);

    }
});

controller.js

import Ember from 'ember';

const {Controller, set, get} = Ember;

export default Controller.extend({

  actions: {
    // Note CRUD.. 
    store() {
        let note = get(this, 'note');
        set(note, 'contact', get(this, 'contact'));
        note.save();
        this.send('reset');
    },
    reset() {
        set(this, 'note', this.store.createRecord('note'));
    }

  },

});

template.hbs

{{#em-form model=note action="store"}}
  {{em-text rows="3" property="content" label="Note" placeholder="Enter a note..."}}
  <button type="button" class="btn btn-default" {{action "reset"}}>Reset</button>
{{/em-form}}

<ul>
  {{#each notes as |note|}}
    <li>{{note.content}}</li>
  {{/each}}
</ul>




Aucun commentaire:

Enregistrer un commentaire