3

I have a redux state using redux-observable's epics.

I need to solve showing a message after a user deletes an object or more objects.

There are two ways how to delete an object:

  1. by action deleteObject(id: string) which call deleteObjectFulfilled action
  2. by action deleteObjects(ids: Array<string>) which call N * deleteObject(id: string) actions

I want to show only one message with a count of deleted messages after every success "deleting action".

My final solution of this epic is:

export const showDeleteInformationEpic = action$ =>
  combineLatest(
    action$.pipe(ofType(DELETE_OBJECT_FULFILLED)),
    action$.pipe(
      ofType(DELETE_OBJECTS),
      switchMap(({ meta: { ids } }) =>
        action$.pipe(
          ofType(DELETE_OBJECT_FULFILLED),
          skip(ids.length - 1),
          map(() => ids.length),
          startWith('BATCH_IN_PROGRESS'),
          take(2),
        ),
      ),
      startWith(1),
    ),
  ).pipe(
    startWith([null, null]),
    pairwise(),
    map(([[, previousCount], [, currentCount]]) => 
      (previousCount === 'BATCH_IN_PROGRESS') 
        ? currentCount 
        : isNumber(currentCount) ? 1 : currentCount),
    filter(isNumber),
    map((count) => throwInfo('objectDeleted', { count })),
  );

Can you see any better solution of this?

tomaass
  • 61
  • 2

2 Answers2

1

There is more simple solution if I use only deleteObjects(Array<string>) for both cases..

tomaass
  • 61
  • 2
1

Instead of firing multiple actions, you can create and dispatch a single action DELETE_MULTIPLE and pass all the id(s) in the payload.

This way your effects will be a lot cleaner since you only have to subscribe to DELETE_MANY action and additionally, it will prevent multiple store dispatches.

Pankaj
  • 538
  • 4
  • 13