Using async fetch inside a concatMap, does not return multiple actions

188 Views Asked by At

I've recently checked this material (https://thecodebarbarian.com/a-beginners-guide-to-redux-observable.html) and tried something with a fetch request the way it says it's supposed to be, e.g.

import { fetchCharactersAction, setCharactersList, setError } from 'models/actions/characterActions';
import { ofType } from 'redux-observable';
import { concatMap } from 'rxjs/operators';

const fetchCharactersEpic = action$ =>
  action$.pipe(
    ofType(fetchCharactersAction.type),
    concatMap(async ({ payload: { name, status, gender, page } }) => {
      const url = `${process.env.REACT_APP_RICKANDMORTY}/character?page=${page}&name=${name}&status=${status}&gender=${gender}`;
      const characters = await fetch(url);
      const returnedCharacters = await characters.json();

      if (returnedCharacters?.error === '' || !returnedCharacters?.error) {
        return setCharactersList(returnedCharacters);
      }

      return setError(returnedCharacters?.error);
    })
  );

This seems just fine, but when I try to return multiple actions inside an array e.g.

return [setCharactersList(returnedCharacters), action2(), action3(), ...]

it says "actions must be plain objects. use custom middleware for async actions"

The actions I am trying to return are all created with the createAction of redux toolkit, but the weird thing is that when they are returned as single, there is no problem. The problem is caused when trying to return multiple actions.

Any idea?

1

There are 1 best solutions below

0
WayneC On

You need to return an observable that concatMap will merge in, so use return of(setCharactersList(returnedCharacters), action2(), action3(), ...)