NGXS how to access setState and patchState without the ctx argument?

58 Views Asked by At

I'm trying to refactor my state by creating a reusable function that handles a patch. How can I access setState and patchState without this strange context argument?

updateThings(ctx: StateContext<TaskStateModel>, { payload }: any): any {
  ctx.setState(
    patch({
1

There are 1 best solutions below

0
Dinesh On

I am not sure if this addresses your concern. But you could destructure the code a bit so you don't have to use ctx.patchState(), etc, etc.

updateThings({patchState}: StateContext<TaskStateModel>, { payload }: any): Observable<any> {
  patchState({
    // your state.
  });
}

Note - I should also mention patchState would only patch the top level attributes. If you have a deeply nested state object you will have to manage the merging yourself. Technically you want to break them out to their own state.

for eg:

updateThings({getState, patchState}: StateContext<TaskStateModel>, { payload }: any): Observable<any> {
  patchState({
     firstLevelObj: {
       ...getState().firstLevelObj,  // Manually merging the object
       secondLevelObj: {
         ...getState().secondLevelObj,  // Manually merging the object
         attribute5: 'newvalue' // Now you can modify just the attribut that you want to patch.
       }
     }
  });
}