3

I am trying to dispatch multiple actions to redux. Here is my code

 action$.pipe(
    ofType(trigger),
    mergeMap(({ payload }) =>
      from(endpoint(payload)).pipe(
        map(response =>

          // this works fine
          // setData(response.data)

          // this doesn't
          concat(
            of(setData(response.data)),
            of({ type: 'hello' })
          )

          // I also tried
          [
            of(setData(response.data)),
            of({ type: 'hello' })
          ]

        )
      )
    ),

    catchError(err => Promise.resolve(creators.setError(err)))
  )

Single dispatch works, but if I try multiple items as above I am getting Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.

Adam
  • 3,415
  • 4
  • 30
  • 49
  • Possible duplicate of [dispatch multiple actions with redux-observable](https://stackoverflow.com/questions/56509064/dispatch-multiple-actions-with-redux-observable) – Harald Gliebe Jun 21 '19 at 10:21

1 Answers1

4

map just maps one item to another so when you return [action1, action2] you're still returning an array and redux-observable tries to treat it as an action itself. What you want instead is "unwrapping" the array (or Observable created with concat) returned.

So instead of using map you can use mergeMap (or concatMap) and when you return an array it'll iterate it and make separate emissions for each item:

mergeMap(response => [
  setData(response.data),
  { type: 'hello' },
]),

If this looks too odd you can wrap the array with from to make it more obvious:

mergeMap(response => from([
  setData(response.data),
  { type: 'hello' },
])),

You can even use a single of:

mergeMap(response => of(
  setData(response.data),
  { type: 'hello' },
)),
martin
  • 93,354
  • 25
  • 191
  • 226
  • Thank you so much for this. I spent a day trying to figure it out. `mergeMap` is what I was missing. – Adam Jun 21 '19 at 10:34
  • switchMap could work as an alternative in some cases. switchMap(() => [action1, action2]) –  Jun 25 '19 at 14:27