samedi 25 juillet 2020

Append record onto RecordArray and Dynamically update Component Template

For the base setup of the app referenced in this question, I am using the Ember Guides Tutorial App.

Here is the route specified in my router.js

// router.js
import EmberRouter from '@ember/routing/router';
import config from './config/environment';

export default class Router extends EmberRouter {
  location = config.locationType;
  rootURL = config.rootURL;
}

Router.map(function() {
  this.route('testing');
});

Here is my route which returns a RecordArray of rental records:

// testing.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class IndexRoute extends Route {

  @service store;

  model() {
    return this.store.findAll('rental');
  }
}

Here is my rental model:

// rental.js
import Model, { attr } from '@ember-data/model';

export default class RentalModel extends Model {
  @attr title;
}

My testing template:

//templates/testing.hbs
<MyComp @rentals= />

My MyComp component template:

// components/my-comp.hbs
<h2>Practice Iterate over RecordArray and Add items</h2>

<ul>
  
    <li></li>
  
</ul>

<button type="button" >Add an object</button>

Lastly, my accompanying MyComp component class:

// components/my-comp.js
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { A } from '@ember/array';

export default class MyCompComponent extends Component {
  @tracked myRentals = this.args;

  @action
  addRental() {
    this.myRentals.pushObject({
      title: "My new rental"
    });
  }
}

Here is what the rendered component looks like:

Rendered component

What I expect is that when I click that "Add an object" button, it creates a new Rental record, and it appends that Rental record to the existing RecordArray. Since that RecordArray is tracked, the component template re-renders, and thus the new record's title attribute displays in the template.

When I click the Button, it returns this error in Web Inspector:

Uncaught TypeError: this.myrentals.pushObject is not a function at MyCompComponent.addRental

I did reference the Ember JS Looping Through Lists Guide. I am clearly missing one or more concepts at work here.

Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire