Sawtaytoes
9/30/2018 - 8:17 AM

Fetching Multiple of the Same Data with AJAX

Redux-Observable will cancel the previous observable when using switchMap so you'll want to use mergeMap instead. That means you need some way of canceling when many dynamic observables exist.

const ofPermissionType = (
  requiredPermissionType,
) => (
  filter(({ permissionType }) => (
    requiredPermissionType === permissionType 
  ))
)

const fetchPermissionEpic = (
  action$,
  state$,
  { ajax },
) => (
  action$
  .pipe(
    ofType(FETCH_PERMISSION),
    mergeMap(({
      permissionType,
    }) => (
      of(state$.value)
      .pipe(
        takeUntil(
          action$
          .pipe(
            ofType(FETCH_PERMISSION),
            ofPermissionType(permissionType),
          )
        ),
        map(accessTokenSelector),
        switchMap(accessToken => (
          ajax({
            crossDomain: true,
            headers: {
              'Authorization': `Bearer ${accessToken}`,
            },
            url: (
              'https://example.com/permissions'
              .concat('?')
              .concat('permissionType=')
              .concat(permissionType)
            ),
          })
          .pipe(
            pluck('response'),
            map(permissionValue => ({
              permissionType,
              permissionValue,
            })),
            map(storePermission),
          )
        )),
      )
    )),
  )
)