Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 :)

like image 552
alan_langlois Avatar asked Mar 07 '18 15:03

alan_langlois


People also ask

Can I use async in reducer?

Show activity on this post. Yes.

Is react reducer async?

Introduction. React useReducer doesn't support async actions natively. Unlike Redux, there's no middleware interface, but hooks are composable. This is a tiny library to extend useReducer's dispatch so that dispatching async actions invoke async functions.

Is react Redux asynchronous?

By default, Redux's actions are dispatched synchronously, which is a problem for any non-trivial app that needs to communicate with an external API or perform side effects. Redux also allows for middleware that sits between an action being dispatched and the action reaching the reducers.

How can async actions handled in Redux?

That function asynchronously fetches books using the Google Books API, and at various stages of the asynchronous fetch, it dispatches other actions by creating the actions with an action creator and dispatching it with the Redux dispatch() function. The fetching actions are handled by the fetch reducer.


2 Answers

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 !

like image 131
SherylHohman Avatar answered Oct 02 '22 01:10

SherylHohman


In a project that I work on, we put the asynchronous code in actions and use "middleware" called "thunk" to resolve the promises to objects which can be consumed by our reducers. All of the reducers are written as synchronous methods which take state and an action and return a new state.

like image 43
Code-Apprentice Avatar answered Oct 02 '22 00:10

Code-Apprentice