How to add an element to an array in ngrx with patchState (Angular Signal Store)

30 views Asked by At

I have a State:

type MyState = {
    elements: ElementDTO[] | undefined,
};

And a NGRX - Signal Store:

export const ElementStore = signalStore(
{providedIn: "root"},
withState<ElementState>(initialState),
.
.
withMethods((store) => ({
    .
    .
    pushElement(element: ElementDTO): void {
        patchState(store, {
            elements: [...store.elements(), element]
        });
    }
    })
    ),
)

But i get the error:

error TS2488: Type 'ElementDTO[] | undefined' must have a 'Symbol.iterator' method that returns an iterator.

What is wrong here?

1

There are 1 answers

1
Gatschet On

After hours of trying, this seems to work

  pushActivation(element: ElementDTO): void {
      patchState(store, {
           elements: [...store.elements() as ElementDTO[], element]
      });
  }

The strange thing is that IntelliJ still shows an error on this line. However, the app compiles and seems to run. The syntax of ngrx seems to be straight from hell!