Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Can't add property 12, object is not extensible

I can't seem to understand the error I am getting on my client application. I am subscribing to a graphql subscription and I am able to retrieve the updates but I am not being able to push the changes to the typescript array called "models:ModelClass[]" which is bound to the view.

Is there something I am missing or doing wrong?

models.component.ts

this.apollo.subscribe({
  query: gql`
    subscription {
      newModelCreated{
        _id
        name
        type
        train_status
        deploy_status
        data_path
        description
        created_at
        updated_at
      }
    }
  `
}).subscribe((data) => {
  console.log("CREATED: " + JSON.stringify(data.newModelCreated));
  console.log(data.newModelCreated);
  var temp:ModelClass = data.newModelCreated;
  this.models.push(temp);
});

model-class.ts

export interface ModelClass {
    _id: string;
    name: string;
    type: string;
    parameters: {
        alpha: number;
    };
    train_status: string;
    deploy_status: string;
    test_accuracy: string;
    created_at: number;
    updated_at: number;
}
like image 569
cyberbeast Avatar asked Apr 22 '17 18:04

cyberbeast


People also ask

How do you fix an object is not extensible?

To fix this error, you will either need to remove the call to Object. preventExtensions() entirely, or move it to a position so that the property is added earlier and only later the object is marked as non-extensible. Of course you can also remove the property that was attempted to be added, if you don't need it.

Is JavaScript arrays are extensible?

Built-in classes like Array, Map and others are extendable also.

How do I remove preventExtensions?

There is no way to make an object extensible again once it has been made non-extensible. It is important to note that Object. preventExtensions only prevents the extension of the top level of the object.


1 Answers

I suppose this.models is an array returned by Apollo and you want to add new created object to your initial array ? If true, Apollo returns an immutable Object !

You have to clone the initial returned array. Something like in the subscribe function:

this.apollo
    .watchQuery({query: INITIAL_GQL_REQUEST})
    .subscribe((data) => {
        this.models = data.models.map((model) => {
            return {
                id: model.id, 
                name: model.name,
                another: model.another
            }
        })
    };
});

Then your subscription request will be able to add a created model to this plain javascript array.

PS: Not sure but I suppose Apollo returns immutable objects because they are stored in the store and depending on your fetch policy, it can miss store hits if your are able to mutate them.

Hope it helps

like image 197
Eric Taix Avatar answered Oct 20 '22 07:10

Eric Taix