shahsank3t
shahsank3t

Reputation: 252

Pushing array of string data in model in ember

I have an API response that returns something like this

{
  texts: ["Text1", "Text2", "Text3"]
}

I have created the Ember model as follow (text.js - model file)

import DS from 'ember-data';
export default DS.Model.extend({});

I am unsure of what to add in the attributes for the model since the response is an array of string.

I am also getting

You must include an 'id' for text in an object passed to 'push'

error with the above snippet.

I am new to ember.js and kind of badly stuck at this point.

Upvotes: 0

Views: 661

Answers (1)

Gaurav
Gaurav

Reputation: 12796

This is not a particularly good API. But sometimes, you don't control the api and just have to make it work with Ember.

I recommend using the array transform provided here: https://gist.github.com/NuckChorris/927d7d4ba757abd26b30#file-array-js

Here is the code:

import Ember from 'ember';
import DS from 'ember-data';

export default DS.Transform.extend({
  deserialize: function(value) {
    if (Ember.isArray(value)) {
      return Ember.A(value);
    } else {
      return Ember.A();
    }
  },
  serialize: function(value) {
    if (Ember.isArray(value)) {
      return Ember.A(value);
    } else {
      return Ember.A();
    }
  }
});

Copy and paste this code into app/transforms/array.js.

Then you will be able to do:

import DS from 'ember-data';
export default DS.Model.extend({
  texts: DS.attr('array')
});

For more information on transforms, look in the guides here: https://guides.emberjs.com/v3.4.0/models/defining-models/#toc_transforms

Upvotes: 1

Related Questions