3

In a client project I use NGRX/Store and NGRX/Entity.

While the majority of the store consists of the Entities, I have to store additional values in the state. For business reasons, I need the length of all items at a certain point in time.

export interface State extends EntityState<Item> {
  initialItemListSize: number; // this should hold the length of entity-adapters items-list-size at a certain point
}

Anyway, at some point I just want to

this.store.dispactch(saveItemListSizeNow);

call.

Now I'm wondering where I have to implement the logic (get the list length).

At first I thought in the reducer

on(Itemctions.saveItemListSizeNow, (state) => {
    const size = ... //<--- no Idea how to get the length here
    return { ...state, initialItemListSize: size };
  }),

Can someone give me an answer?

EchtFettigerKeks
  • 1,692
  • 1
  • 18
  • 33

2 Answers2

2

You can access the entities on the state.

state.ids.length

E.g.:

on(Itemctions.saveItemListSizeNow, (state) => {
    const size = ... //<--- no Idea how to get the length here
    return { ...state, initialItemListSize: state.ids.length};
  }),
timdeschryver
  • 14,415
  • 1
  • 19
  • 32
0

Your actions can be defined with payloads data that can be passed on dispatching it, example:

import { createAction, props } from '@ngrx/store';

export const saveItemListSizeNow= createAction(
  '[Action Source] Save Item list size',
  props<{ itemListSize: number }>()
);

And when you dispatch it,

store.dispatch(saveItemListSizeNow({ itemListSize: givenSize }));

And your reducer would be like this

on(Itemctions.saveItemListSizeNow, (state, action) => {
  const size = action.itemListSize;
  return { ...state, initialItemListSize: size };
}),
fujy
  • 5,168
  • 5
  • 31
  • 50