The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error

cannot read property 'setDirtyAttribute' of null
even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject.

Model:

import DS from 'ember-data';
import {computed} from "@ember/object";

export default class Person extends DS.Model {
  @DS.attr() firstName!: string;
  @DS.attr() lastName!: string;
  @DS.attr() age!: number;
  @DS.attr() desc?: string;

  @computed("firstName", "lastName")
  public get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

Route:

export default class Persons extends Route {
  @service() public store!: DS.Store;

  constructor() {
    super(...arguments);

    const persons: Person[] = [
      Person.create({firstName: "first1", lastName: "last1", age: 10}),
      Person.create({firstName: "first2", lastName: "last2", age: 320}),
      Person.create({firstName: "first3", lastName: "last3", age: 30}),
    ];
      persons.forEach(p => this.store.createRecord('person', p));
  }
}

Error message upon entering the page:

Uncaught TypeError: Cannot read property 'setDirtyAttribute' of null
    at Person.set (-private.js:144)
    at ComputedProperty._set (metal.js:3543)
    at ComputedProperty.setWithSuspend (metal.js:3532)
    at ComputedProperty.set (metal.js:3503)
    at initialize (core_object.js:67)
    at Function.create (core_object.js:692)
    at new Persons (persons.js:23)
    at Function.create (core_object.js:684)
    at FactoryManager.create (container.js:549)
    at instantiateFactory (container.js:359)

As a solution, using

this.store.createRecord('person', {firstName: "first1", lastName: "last1", age: 10})
instead of
this.store.createRecord('person', <a Person class instance>)
is required, deviating from TypeScript standards. Seeking advice on a more elegant way to merge ember features with TypeScript without resorting to any or plain object.

Any suggestions?

Answer №1

The Ember Data documentation emphasizes avoiding the use of Model.create({}). It is noted that this method is considered private API, and instances of models should only be created using the store service:

Create should only ever be called by the store. To create an instance of a Model in a dirty state use store.createRecord.

To create instances of Model in a clean state, use store.push

Ember Data's public APIs are designed to work seamlessly with Typescript. The previously reported bug in

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a727d7a6d327b7e6b7e5f2c312e2e31abbcbebfadbaebde">[email protected]</a>
should have been resolved in a subsequent update.

For guidance on setting up Ember Data support with TypeScript, please consult Ember CLI TypeScript's documentation regarding Ember Data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying JavaScript Array Elements in an Aligned Table Format

Unfortunately, I accidentally deleted my previous post and now need to repost it. I have a code that is functioning well, thanks to the great help I received here. However, the output of the array players is not neatly aligned with each other in a table f ...

jQuery's capability to select multiple elements simultaneously appears to be malfunctioning

I am dynamically creating div elements with unique ids and adding span elements with specific CSS properties. $(".main").append("<div class=largeBox id=" + counter + "</div>"); $(".largeBox").append("<span class=mainTitle></span>"); ...

I am encountering issues with my PostCSS plugin not functioning properly within a Vue-cli 3 project

I developed a custom postcss plugin that was working perfectly according to the postcss guidelines until I tried to implement it in a real project. For reference, here's the plugin on GitHub My goal is to integrate it into a Vue-cli app using Webpac ...

When using the v-for directive with an array passed as props, an error is

I encountered an issue while passing an array of objects from parent to child and looping over it using v-for. The error message "TypeError: Cannot read property 'title' of undefined" keeps appearing. My parent component is named postsList, whil ...

When attempting to pass a token in the header using AngularJS, I encounter an issue with my NodeJS server

Error is: Possibly unhandled Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11) at ServerResponse.res.set.res.header 1. All Node.js services were functioning properly before ...

An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results. As I am currently testing on a local server, the desired request URL is http://127.0.0.1:800 ...

Check if an element possesses a specific property and corresponding value in JavaScript

I was looking to determine if an object has a specific property with a certain value, and wanted to search for it within an array of objects. var test = [{name : "joey", age: 15}, {name: "hell", age: 12}] After testing the code snippet below, I realized ...

After the form is successfully submitted, you can remove the required attribute

Upon clicking the submit button of a form, an input box is highlighted with a red border if empty. After successful jQuery AJAX form submission, a message "data submitted" is displayed and the form is reset causing all input fields to be highlighted in red ...

Matter of Representing Nested For Loops in Javascript Arrays

When I have two arrays that intersect at certain elements, the resulting function should ideally output A, B, Y. However, in this case, it displays all possible combinations of lista.length * listb.length. <script> window.onload = function(){ ...

Parsing JSON results in the return of two objects

I am analyzing a JSON file, expecting it to return Message[] using a promise. This code is similar to the one utilized in the Heroes sample project found in HTTP documentation { "data": [ {"id":"1","commid":"0","subject":"test1subject","body":" ...

Having trouble confirming signature with Node.js Crypto library, specifically with key pairs

I have a concise nodejs code snippet where I attempt to sign a string and then verify it using node crypto along with key pairs generated through openssl. Despite trying various methods, the result consistently shows "false" indicating that the signature c ...

A simple guide to positioning an image between two lines of text with Material UI

I am trying to design a banner area with an icon on the left and two lines of text (title and sub-title) in the middle. However, when I implement this structure, each element appears on a separate line. You can view the issue here: https://codesandbox.io/ ...

Came across some code where I was reading the source and stumbled upon `const {foo} = foo;

I recently encountered the line of code const {foo} = foo in my JavaScript studies. I'm having trouble understanding its meaning despite multiple attempts. Can anyone provide a clear explanation for this please? ...

Is JavaScript's setTimeout 0 feature delaying the rendering of the page?

Based on information from this StackOverflow post The process of changing the DOM occurs synchronously, while rendering the DOM actually takes place after the JavaScript stack has cleared. Furthermore, according to this document from Google, a screen r ...

The Vue event was triggered, however there was no response

My current project consists of a Typescript + Vue application with one parent object and one component, which is the pager: //pager.ts @Component({ name: "pager", template: require("text!./pager.html") }) export default class Pager extends Vue { ...

The Fusion of Ember.js and Socket.io: Revolutionizing Web

I have been trying to incorporate a basic Ember application into the view of my node application. I have verified that Ember is properly set up and my sockets are functioning correctly. However, I am encountering an issue where the data is not being displa ...

Sequelizejs establishes a belongsToMany relation with a specified otherKey

I am currently developing an app centered around songs and artists, and here is the database schema I have designed: Each Song can have multiple Artists associated with it, and each Artist can be linked to several Songs as well. This establishes a many-to ...

Oops! The system encountered a problem while trying to identify the value `Han` for the property `Script

I'm attempting to extract Chinese characters from a string. According to this particular answer, the following code snippet should work: const nonChinese = /[^\p{Script=Han}]/gimu; const text = "asdP asfasf这些年asfagg 我开源的 几 ...

The endless $digest loop issue arises when attempting to filter an array of objects

Encountered a persistent $digest loop issue while passing parameters to a custom filter defined on the $scope. Here's the snippet in HTML: <ul id="albumListUL" class="fa-ul"> <li ng-repeat="album in GoogleList | myFilter:Field:Reverse t ...

Error encountered during Jest snapshot testing: Attempting to destructure a non-iterable object which is invalid

I am currently facing an issue with my React codebase where I am attempting to create snapshot tests for a component. However, Jest is showing an error indicating that I am trying to destructure a non-iterable instance. Despite thoroughly reviewing the cod ...