Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

reactjs - React Redux - Is adding async method in a Reducer an anti pattern?

I'm pretty new to the whole react-native / redux world, so maybe this question will sound dumb :)

I know that for an API call, or stuff like that, the convention is to use middleware, but is it always necessary? (It adds a lot of boilerplate).

I succefully added an async method in a reducer to manage a device API connection, such as In-App or Local Notifications, but I wonder if it is ok to handle it this way.

For instance, in my reducer there is this method:

function initInApp(state, itemSkus){
  init(state, itemSkus);
  return {
    ...state,
    itemSkus: itemSkus,
  }
}

And this one, which manage the async part:

async function init(state, itemSkus){
  try {
    if( !state.isInit ){
      const prepare = await Promise.all(RNIap.prepareAndroid());
      return{
        ...state,
        isInit: true,
        errorCode: false,
      }
    }
    else {
       return ...state;
    }
  } catch (errorCode) {
    return{
      ...state,
      isInit: false,
      errorCode: errorCode,
      itemSkus: itemSkus
    }
  }
}

Maybe it's not efficient in terms of performances or hard to maintain..What are your thoughts on this?

Thanks :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes. Reducers should not have any side effects. Reducers need to be Pure Functions for redux to work efficiently. Here are a couple links that attempt to explain why redux needs reducers to be pure functions and why are pure reducers so important in redux.

As others indicated thunk middleware is a common way to handle asynch in react.

Another method, that does not require any library is through a pattern known as "Fat Action Creators". Action creators can handle asynch operations. The way they do this is by returning a "dispatch" wrapper around the function, so it can itself dispatch actions.

Here is an example of this taken from the Medium Article:
Where Do I Put my Business Logic In a React-Redux Application
(This article is also linked to from the redux FAQ):

const fetchUser = (dispatch, id) => {
  dispatch({ type: USER_FETCH, payload: id });
  axios.get(`https://server/user/${id}`)
   .then(resp => resp.data)
   .then(user => dispatch({ type: USER_FETCH_SUCCESS, 
                            payload: user }))
   .catch(err => {
     console.error(err); // log since might be a render err
     dispatch({ type: USER_FETCH_FAILED, 
                            payload: err, 
                            error: true });
   });
};

Packages other than redux-thunk include:

  • https://www.npmjs.com/package/redux-logic

    "One place for all your business logic and action side effects" "With redux-logic, you have the freedom to write your logic in your favorite JS style:`

    • plain callback code - dispatch(resultAction)
    • promises - return axios.get(url).then(...)
    • async/await - result = await fetch(url)
    • observables - ob$.next(action1)`
  • redux-saga

    redux-saga is a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, simple to test, and better at handling failures. uses generators so make sure you're confortable using them.

  • redux-observable, if you prefer RxJS Observables
    This library was created by Jay Phelps, and this medium post "redux-observable" was written by Ben Lesh. Both well known in the react community.

  • redux-thunk For completeness.

  • Additional packages are listed in the article mentioned earlier:
    Where Do I Put my Business Logic In a React-Redux Application

All the Best !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...