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 :)
Show activity on this post. Yes.
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.
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.
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.
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 !
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With