I am recently learning Angular with @ngrx/store while one of the tutorial is to use @ngrx/store for state management, I'm trying to use ngrx to add data in a table ( table from angular material ) using input but I have an error that I don't understand, I'm quite junior and I don't know ngrx at all.
here is my error : TypeError: Cannot read properties of undefined (reading 'id') the error comes from the reducer
ts.file
export class AppComponent implements OnInit, OnDestroy {
private ELEMENT_DATA!: PeriodicElement[];
public displayedColumns: string[] = ['name'];
public dataSource = new MatTableDataSource<PeriodicElement>(
this.ELEMENT_DATA
);
public tableName!: Observable<PeriodicElement[]>;
constructor(
private tableService: TableService,
private store: Store<reducer.State>
) {
this.tableName = store.select(tableSelector.selectAll);
}
ngOnInit(): void {
this.store.select(tableSelector.selectAll).subscribe((res) => {});
this.get();
}
get() {
this.tableService
.getTableDetails()
.subscribe((data: any) => {
this.dataSource.data = data;
});
}
add(name: any) {
this.store.dispatch({ type: action.Add });
// this.tableService.create(name).subscribe((data: string) => {
// this.get();
// });
}
action.ts
export const Add = '[PeriodicElement] Add';
export const addTable = createAction(
Add, props<{payload:PeriodicElement}>()
)
export class AddPeriodicElement implements Action {
readonly type = Add;
constructor(public payload: PeriodicElement) {}
}
export type Actions = AddPeriodicElement;
reducer.ts
export const tableAdapter: EntityAdapter<PeriodicElement> =
createEntityAdapter<PeriodicElement>({});
export interface State extends EntityState<PeriodicElement> {}
export const initialeState: State = tableAdapter.getInitialState();
const tableReducer = createReducer(
initialeState,
on(TableActions.addTable, (state, { payload}) => {
console.log('state', state);
console.log('payload', payload);
return tableAdapter.addOne(payload, state);
})
);
export function reducer(state: State | undefined, action: Action) {
return tableReducer(state, action);
}
selector.ts
export const getTable = createFeatureSelector<tableReducer.State>('toto');
export const { selectAll } = tableReducer.tableAdapter.getSelectors(getTable);
interface
export interface PeriodicElement {
name: string;
}