platform icon indicating copy to clipboard operation
platform copied to clipboard

@ngrx/operators: add `mapResponse`

Open markostanimirovic opened this issue 1 year ago • 0 comments

Which @ngrx/* package(s) are relevant/related to the feature request?

operators

Information

Similar to tapResponse, add mapResponse operator to improve response handling in NgRx effects.

Before:

export const loadAllUsers = createEffect((
  actions$ = inject(Actions),
  usersService = inject(UsersService)
) => {
  return actions$.pipe(
    ofType(UsersPageActions.opened),
    exhaustMap(() => {
      return usersService.getAll().pipe(
        map((users) => UsersApiActions.usersLoadedSuccess({ users })),
        catchError((error) =>
          of(UsersApiActions.usersLoadedFailure({ error }))
        )
      );
    })
  );
});

After:

import { mapResponse } from '@ngrx/operators';

export const loadAllUsers = createEffect((
  actions$ = inject(Actions),
  usersService = inject(UsersService)
) => {
  return actions$.pipe(
    ofType(UsersPageActions.opened),
    exhaustMap(() => {
      return usersService.getAll().pipe(
        mapResponse({
          next: (users) => UsersApiActions.usersLoadedSuccess({ users }),
          error: (error) => UsersApiActions.usersLoadedFailure({ error }),
        })
      );
    })
  );
});

Describe any alternatives/workarounds you're currently using

No response

I would be willing to submit a PR to fix this issue

  • [X] Yes
  • [ ] No

markostanimirovic avatar Feb 02 '24 23:02 markostanimirovic