David B
David B

Reputation: 355

Ember Data findAll() causing "TypeError: Cannot read property 'type' of undefined"

Hooking up my 1st model to my backend and am getting the following error when calling Ember Data's findAll()

TypeError: Cannot read property 'type' of undefined

The route,

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        this.store.findAll('restaurant');
    }
});

The model,

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr()
});

I can see that Ember is hitting my local server and returning properly formatted JSON from the correct url,

{  
    "restaurants": {  
        "id":1,
        "name":"Restaurant Name"
    }
}

I have seen similar questions about this but it usually has to do with improperly formatted JSON.

Upvotes: 0

Views: 1574

Answers (2)

JoannaFalkowska
JoannaFalkowska

Reputation: 3677

Your JSON file is formatted like a REST API response, but by default Ember uses JSONAPIAdapter.

First fix the JSON, it should return an array:

[{  
  "id":1,
  "name":"Restaurant Name"
}]

Then change the adapter and configure serializer:

// in app/adapters/application.js

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

export default DS.RESTAdapter.extend({
})


// in app/serializers/application.js

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

export default DS.JSONSerializer.extend({
})

Read more:

Customizing adapters

JSONAPIAdapter

RESTAdapter

Upvotes: 1

XYZ
XYZ

Reputation: 27387

The default data format Ember data used is JSON API so your data should look something like below,

{
  "data": {
    "id": "1",
    "type": "restaurants,
    "attributes": {
      "name": "Name"
    }
  }
}

To make Ember data fit your needs without change how backend produce data's format. You can add your own adapter which is used to transfer your Ember data's request to the right request.

Read more about the adapter at the link below,

https://guides.emberjs.com/v2.6.0/models/customizing-adapters/

Upvotes: 2

Related Questions