esamattis / immer-reducer

Type-safe and terse reducers with Typescript for React Hooks and Redux
http://npm.im/immer-reducer
MIT License
224 stars 15 forks source link

Redux-Saga api calls #40

Open promontis opened 5 years ago

promontis commented 5 years ago

Hi @epeli!

I was wondering how you implement Redux-Saga API calls.

If I take the default Redux-Saga readme example:

import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import Api from '...'

// worker Saga: will be fired on USER_FETCH_REQUESTED actions
function* fetchUser(action) {
   try {
      const user = yield call(Api.fetchUser, action.payload.userId);
      yield put({type: "USER_FETCH_SUCCEEDED", user: user});
   } catch (e) {
      yield put({type: "USER_FETCH_FAILED", message: e.message});
   }
}

/*
  Starts fetchUser on each dispatched `USER_FETCH_REQUESTED` action.
  Allows concurrent fetches of user.
*/
function* mySaga() {
  yield takeEvery("USER_FETCH_REQUESTED", fetchUser);
}

The pattern is to dispatch an action (USER_FETCH_REQUESTED ) and handle it in the saga. The saga calls the API and puts the result to either USER_FETCH_SUCCEEDED or USER_FETCH_FAILED.

Now when modeling this in immer-reducer would I get the following?

Seems kinda weird... especially the empty method just for creating an action.

Would love to hear your view on this.

Thanks,

Michel

yrral86 commented 4 years ago

The method you outlined is how I'm doing it. However, if the empty method bothers you, I don't see why you couldn't create a normal action creator function and check for that action type in your saga and keep immer-reducer just for actions that mutate state.