If you have multiple objects to add in ngrx state, how can you ensure they are all captured and kept in sync?
For example, what if one user is associated with more than one task? Currently, when all tasks are returned, the store is updated twice. However, each update replaces the last task with a new one. This behavior is expected, but how can you initialize an array to capture updates as an array of objects and keep them synchronized?
task.reducer.ts
import * as TaskActions from './task.actions';
import { Action, createReducer, on } from '@ngrx/store';
import { ITask } from '../../models/task';
export interface State {
task: ITask | null;
error: any;
}
const initialState: ITask = {
basketTotal: 0,
carePlanPrice: 0,
category: null,
completionDate: null
};
export const taskReducer = createReducer(
initialState,
on(TaskActions.getData, state => ({ ...state })),
on(TaskActions.dataReceived, (state, payload) => ({ ...state, payload })),
on(TaskActions.dataNotReceived, state => ({ ...state })),
on(TaskActions.signOut, state => ({ ...state })),
on(TaskActions.signOutSuccess, state => ({ ...state, ...initialState })),
);
export function reducer(state: ITask | undefined, action: Action) {
return taskReducer(state, action);
}
task.effect.ts
@Effect()
getData$ = this.actions$.pipe(
ofType(TaskActions.getData),
switchMap(() => {
return this.afs.collection<ITask>('tasks', ref =>
ref.where('createdBy', '==', localStorage.getItem('uid'))).stateChanges().pipe(
);
}),
mergeMap(actions => actions),
map(action => {
if (action.payload) {
return TaskActions.dataReceived({ payload: TaskService.parseData(action.payload.doc.data()) });
} else {
return TaskActions.dataNotReceived();
}
})
);
task.actions.ts
import { createAction, props } from '@ngrx/store';
import { ITask } from '../../models/task';
export const getData = createAction('[Task] Get Data');
export const dataReceived = createAction('[Task] Data Received', props<{ payload: Partial<ITask> }>());
export const dataNotReceived = createAction('[Task] Data Not Received');
export const signOut = createAction('[Task] Sign Out');
export const signOutSuccess = createAction('[Task] Sign Out Success');
Update:
I tried
on(TaskActions.dataReceived, (state, payload) =>
({
...state,
tasks: [...state.tasks, payload.payload ]
})),
and this happened:
https://i.sstatic.net/w0iJX.png
I was expecting an array like this:
task: [
{ ... }, { ... }
]