Search code examples
javascriptwordpressember.jsember-datawordpress-rest-api

Cannot read property 'id' of null ember


I am attempting to fetch data from a WordPress application with an Ember application. I am attempting to fetch the menu item in WordPress with the ID of '2'. I am using the ember-wordpress plugin and can successfully get my posts, I am just struggling to grab the menu from the API.

Below is my menu model

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  count: DS.attr('number')
});

Here is my route.

import Ember from 'ember';

export default Ember.Route.extend({

  model() {
    return Ember.RSVP.hash({
      menu: this.store.findRecord('menu', 2)
    });
  }

});

However when I try hit the URL I get the error in my console

Error while processing route: Cannot read property 'id' of null TypeError: Cannot read property 'id' of null

Here is the JSON I am getting from my end point.

{
"ID": 2,
"name": "Main Menu",
"slug": "main-menu",
"description": "",
"count": 2,
"items": [
{
"id": 19,
"order": 1,
"parent": 0,
"title": "Projects",
"url": "http://localhost:8888/ember-wp/projects/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 17,
"object": "page",
"object_slug": "projects",
"type": "post_type",
"type_label": "Page"
},
{
"id": 20,
"order": 2,
"parent": 0,
"title": "Services",
"url": "http://localhost:8888/ember-wp/services/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 15,
"object": "page",
"object_slug": "services",
"type": "post_type",
"type_label": "Page"
}
],
"meta": {
"links": {
"collection": "http://localhost:8888/ember-wp/wp-json/wp/v2/menus/",
"self": "http://localhost:8888/ember-wp/wp-json/wp/v2/menus/2"
}
}
}

Can anyone see where I am going wrong here?


Solution

  • I imagine you're using the WP API Menus plugin to pull down data, as I ran into the same issue. You're going to need to edit one of the files in that plugin to correct this.

    In wp-api-menus-v2.php

    1. On line 108, change $rest_menus[ $i ]['ID'] = $menu['term_id']; to $rest_menus[ $i ]['id'] = $menu['term_id'];
    2. On line 143, change $rest_menu['ID'] = abs( $menu['term_id'] ); to $rest_menu['id'] = abs( $menu['term_id'] );

    Changing those two keys from uppercase to lowercase will solve your problem.