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?