Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2/Typescript/ngRx - TypeError: Cannot assign to read only property of object

In the constructor I do something like this

selectedDate: Object;
// construtor
this.selectedDate = {};
this.selectedDate['date'] = new Date();
this.selectedDate['pristine'] = new Date();

In another function which gets called on a button click I do the following:

this.selectedDate['date'] = new Date(this.selectedDate['pristine']);

And I get the following error:

TypeError: Cannot assign to read only property 'date' of object '[object Object]'

like image 704
Vik Avatar asked Jun 27 '17 16:06

Vik


2 Answers

Credits to Ryan Q:

As Ryan commented I was using ngRx in my app and I was indeed passing this.selectedDate object through an action into the store and hence I was not able to modify the object that is stored in the State.

One way to resolve this is pass a new object reference and this should resolve the issue:

this.store.dispatch(new settime.DateChangeAction(Object.assign({}, this.selectedDate)));
like image 190
Vik Avatar answered Oct 31 '22 05:10

Vik


@vikas' answer put me on the right track to solve a similar issue.

I'm trying to handle an upload, where I want to display the progress:
- From the UploadComponent, I emit an event to the parent
- The parent dispatch an action to the store
- An effect catches the action, call the service to upload the file (which returns an array with two observables: progress$ and result$)
- The effect dispatch an HttpProgress action which contains the observable

And at this point I had a similar issue. After digging into store freeze code, a coworker and I found out that it also deep freeze the action.payload. And thus, passing an observable results into an error as observable state is mutated internally.

I'm not using the payload to keep it into the store, just so I can register to actions$ within my component so here it doesn't matter if I pass a mutable object into the payload. To avoid that error, I just wrapped the observable into a function as deep freeze do not freeze functions.

like image 2
maxime1992 Avatar answered Oct 31 '22 07:10

maxime1992