0
votes

I'm creating a login epic and dispatching multiple actions, the multiple actions are dispatched fine within 'CatchError' but produces an error "Actions must be plain objects. Use custom middleware for async actions." when dispatching the actions within the observable in the 'else' block.

export const loginUserEpic = action$ =>
action$.pipe(
    ofType(LOGIN_USER),
    switchMap(({ payload: { email, password } }) => {
      const body = {
        email: email,
        password: password
      };

  return from(axios.post(`${process.env.REACT_APP_BACKEND}/api/auth/login`, body, config)).pipe(
    map(response => {
      if (response.data.user.is_active) {
        return { type: "LOGIN_SUCCESS", payload: response.data };
      } else {
        return of(
          { type: "USER_LOADING" },
          { type: "TOGGLE_MODAL" },
          updateModalData(modalTypes.EMAIL_SENT, "")
        );
      }
    }),
    catchError(err =>
      of({ type: "LOGIN_FAIL" }, createAlert(alertTypes.RED_ALERT, err.data, err.status))
    )
  );
}));
1
Hmm, I'm not too familiar with react-redux but have you tried returning an array of actions, perhaps like from([action1, action2])? - Daniel B
yep, same problem unfortunately - Jon Flynn
It sounds like createAlert might be creating a non-serializable action? Possibly err.data is non-serializable? But I'm not familiar with observables so I could be totally wrong. - Linda Paiste
that part works fine actually, it's within the 'else' block that's triggering the error. Have tried returning both from/of observables and just an array of actions without an observable and the error always persists. it only works when one single action is returned like the if block above it - Jon Flynn

1 Answers

0
votes

I used mergemap so I could then return an observable:

    export const loginUserEpic = action$ =>
  action$.pipe(
    ofType(LOGIN_USER),
switchMap(({ payload: { email, password } }) => {
  const body = {
    email: email,
    password: password
  };

  return from(axios.post(`${process.env.REACT_APP_BACKEND}/api/auth/login`, body, config)).pipe(
    mergeMap(response => {
      if (response.data.user.is_active) {
        return of({ type: "LOGIN_SUCCESS", payload: response.data });
      } else {
        return of(
          { type: "USER_LOADING" },
          { type: "TOGGLE_MODAL" },
          updateModalData(modalTypes.EMAIL_SENT, "")
        );
      }
    }),
    // takeUntil(actions$.pipe(ofType(CANCEL))),
    catchError(err =>
      of({ type: "LOGIN_FAIL" }, createAlert(alertTypes.RED_ALERT, err.data, err.status))
    )
  );
})

);