The property in the object cannot be assigned because it is read-only: [object Object]

I am currently developing an Ionic application using the Angular framework and NGRX. I have encountered an issue with a selected checkbox.

The problem arises when:

First, I fetch a list of vehicles from a database using a service. Then, I set the property 'selected' to false:

this.vehicleService.loadVehicles().subscribe(data => {
  this.vehicles = data.map(v => { v.selected = false; return v; });
});

Next, I pass the 'vehicles' variable to another component where I display ion-checkboxes:

<app-devices-menu *ngIf="vehicles !== undefined" [vehicles]="vehicles"
  (selectedDevices)="selectedVehicles($event)" (currentDevice)="currentVehicle($event)">
</app-devices-menu>

This is my app-devices-menu component TypeScript file:

@Input() vehicles: VehicleItem[];
@Output() selectedDevices = new EventEmitter<VehicleItem[]>();
@Output() currentDevice = new EventEmitter<VehicleItem>();

constructor() { }
ngOnInit() { }

setSelectedDevices(d: VehicleItem) {
  this.currentDevice.emit(d);
  this.selectedDevices.emit(this.vehicles.filter(v => v.selected === true));
}

HTML:

<ion-menu side="end" class="devices-menu"  menuId="devices" contentId="main">
  <ion-list>
    <ion-item *ngFor="let v of vehicles">
      <ion-checkbox (ionChange)="setSelectedDevices(v)" [(ngModel)]="v.selected" slot="start"></ion-checkbox>
      <ion-label>{{ v.description }}</ion-label>
    </ion-item>
  </ion-list>
</ion-menu>

Everything up to this point works correctly. My goal is to store the current vehicle (the last device clicked) and the list of selected devices in the ngrx store. However, when dispatching the selectedVehicles action and changing the selected property from true to false, I encounter this error message: https://i.sstatic.net/o5L5I.png

This is the function where I receive the event from the other component and dispatch the action:

selectedVehicles(ev: VehicleItem[]) {
  const selectedDevices: VehicleItem[] = [...ev];
  this.store.dispatch(actions.setSelectedVehicles({ vehicles: selectedDevices }));
}

And here is my reducer where I update the array in the store:

const reducerMap = createReducer(initialMapState,    
    /* VEHICLE LIST ---------------------------- */
    on(actions.setSelectedVehicles, (state, { vehicles }) => ({ ...state, selectedVehicles: [...vehicles] })),    
);

export function mapReducer(state, action) {
    return reducerMap(state, action);
}

I suspect that JavaScript works by reference, which may be causing issues with modifying the store. The spread operator '[...]' does not seem to work as expected in creating a new array. How can I resolve this issue and successfully update the store with the selected vehicles and current vehicle?

Answer №1

To find the solution, you can use the following code:

 this.newList = this.list.map((item: any) => ({ ...item }));

After that, you can utilize this new variable in both your HTML and TypeScript files to access the values.

   <ion-item *ngFor="let n of newList; let i = index">
      <ion-checkbox [(ngModel)]="newList[i].selected" slot="start"></ion-checkbox>
      <ion-label>{{ n.description }}</ion-label>
    </ion-item>

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

Troubleshooting problems with data binding in Angular Ionic

Just starting out with Angular and experimenting with building an app in Ionic. I have a screen with 2 input fields and I want to achieve the following. When a user inputs something in the price field, I want the weight field to update accordingly. Simil ...

Angular 4 in combination with ngx-datatable is showing a 404 error for the @swimlane/ngx-datatable package

Just starting out with Angular and I kicked things off by running this command: git clone https://github.com/angular/quickstart appName I've made the upgrade to Angular 4 and everything seems to be in order. Here's the output I got after running ...

"An issue has been noticed with Discord.js and Discordx VoiceStateUpdate where the return

Whenever I attempt to retrieve the user ID, channel, and other information, I receive a response of undefined instead of the actual data import { VoiceState } from "discord.js"; import { Discord, On } from "discordx"; @Discord() export ...

Angular's table data display feature is unfortunately lacking

Below is a simple HTML code snippet: <div class="dialogs"> <div id="wrapper" > <p>{{createTestingConstant()}}</p> <ng-container *ngFor="let one of contacts"> <p>{{one ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

Setting up an nginx configuration that seamlessly integrates an Angular 4 application and a WordPress blog within the same route

Presumption: The current system is hosted on https://example.com [which is statically served from /home/centos/projects/dist.example.com] My attempt was to set up the path https://example.com/blogs to run a WordPress blog application. This is my conf ...

Angular 10 - unable to bind 'formGroup' as it is not recognized as a valid property of 'form'

In my existing Angular application, I need to implement routing and a login page as the functionality expands. To integrate routing, I have included the following code: app.module.ts // Importing various modules @NgModule({ declarations: [ App ...

Exploring TypeScript: Understanding how to define Object types with variable properties names

Having an issue with a React + TypeScript challenge that isn't causing my app to crash, but I still want to resolve this lingering doubt! It's more of a query than a problem! My goal is to set the property names of an object dynamically using va ...

Guide on transforming a Unix timestamp into either "2000-01-01" or "2000-05-24 20:00:00" format, or the opposite way, using Deno

Just starting out with Deno and looking to convert a Unix timestamp such as 1646245390158 into either the format of 2000-01-01 or 2000-05-24 20:00:00, or vice versa. Any tips on how to achieve this? ...

Angular time-based polling with conditions

My current situation involves polling a rest API every 1 second to get a result: interval(1000) .pipe( startWith(0), switchMap(() => this.itemService.getItems(shopId)) ) .subscribe(response => { console.log(r ...

The type '{ children: Element; }' cannot be assigned to the type 'IntrinsicAttributes & ReactNode'

Encountered this error: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes & ReactNode'. export const withAppProvider = (Component: AppComponent) => { return function WrapperComponent(props: any) { ...

Setting the current date in Angular using TypeScript and storing it in a MySQL database

As I delve into learning Angular, I am focused on practicing with a form. Specifically, I am attempting to include the current date when inputting client records along with their RFC, branch, and cost. Unfortunately, my attempts have been unsuccessful in i ...

Store the video file transmitted through a multipart form in Serverless Offline mode

I currently have a website built with Angular4 featuring a basic form for uploading data using ng2-file-upload. The files are sent to a Node.js-based serverless offline server where my goal is to simply save those files received from the form onto disk. A ...

Update the Ngrx reducer when the component is present on the page

One dilemma I am facing involves managing two components within a page - an update user form and a history of events. Each component has its own reducer (user and events). My goal is to update the list of events in the store through an API call once the us ...

Changing function arguments in TypeScript using the spread operator

Could the Tuple spreading syntax in Typescript be utilized to consolidate these function overloads? The challenge lies in the necessity to refactor the function arguments into new types. type Type = TString | TNumber type TString = { tag: 'string&apos ...

Can the type of a prop be specified in the parent component before it is passed down to the children components that utilize the same prop?

In my codebase, I have a component called NotFoundGuard. This component only renders its children if a certain condition is true. Otherwise, it displays a generic fallback component to prevent redundancy in our code. I am trying to figure out if there is ...

Discovering the generic parameter in the return type using TypeScript

I am struggling with a specific issue export type AppThunk<ReturnType> = ThunkAction< ReturnType, RootState, unknown, Action<string> >; After implementing the above code snippet export const loadCourse = (id: string): AppThunk ...

Tips for bringing in a feature that is available in JavaScript but missing in TypeScript definitions and troubleshooting any resulting errors

Utilizing react-native-keyboard-aware-scroll-view, the library has the following exports in their code: export { listenToKeyboardEvents, KeyboardAwareFlatList, KeyboardAwareSectionList, KeyboardAwareScrollView } However, the index.d.ts file does n ...

The error message states that the argument type '(src: Observable<any>) => Observable<any>' cannot be assigned to a parameter of type 'OperatorFunction<Object, any>'

Encountering a typescript error when trying to start the app. Not sure where I'm going wrong. It seems like it could be an issue with the rxjs version, but struggling to find the right solution. Seeing incompatible types on my system and not getting r ...

When switching between npm and ionic in various directories, the versions displayed may vary

I've encountered a strange issue while trying to install ionic and npm. Up until yesterday, I had no problem building an app. However, after attempting to update my ionic version to 2.1.18, I ran into some difficulties. When I checked ionic -v in ...