How to reorganize reduction + thunk action / constants

In my action / redux / thunk application, I use actions like:

function catsRequested() { return { type: CATS_REQUESTED, payload: {}, }; } function catsReceived(landings) { return { type: CATS_RECEIVED, payload: landings, }; } function catsFailed(error) { return { type: CATS_FAILED, payload: { error }, }; } export const fetchCats = () => ((dispatch, getState) => { dispatch(catsRequested()); return catsAPI.loadCats() .then((cats) => { dispatch(catsReceived(cats)); }, (e) => { dispatch(catsFailed(e.message)); }); }); 

To deal with some data (simplified). Everything works, but I have a lot of code for each data object (and constants too). I mean the same functions for dogs, tigers, birds, etc.

I see that for each object there are similar requested / received / failed actions / constants.

What is the correct way to minimize code in terms of redux-thunk?

+5
source share
1 answer

You can save your DRY code by creating thunk types and creators:

A type:

 const createTypes = (type) => ({ request: `${type}_REQUESTED`, received: `${type}_RECEIVED`, failed: `${type}_FAILED`, }); 

Thunk:

 const thunkCreator = (apiCall, callTypes) => ((dispatch, getState) => { dispatch({ type: callTypes.request }); return apiCall .then((payload) => { dispatch({ type: callTypes.received, payload })); }, (e) => { dispatch({ type: callTypes.failed, payload: e.message })); }); }); 

Now you can create a fetch method with two lines of code:

 export const fetchCatsTypes = createTypes('CATS'); // create and export the constants export const fetchCats = (catsAPI.loadCats, fetchCatsTypes); // create and export the thunk export const fetchDogsTypes = createTypes('DOGS'); // create and export the constants export const fetchDogs = (dogsAPI.loadDogs, fetchDogsTypes ); // create and export the thunk 

Note: you will also use constant types ( fetchDogsTypes ) in reducers.

+5
source

Source: https://habr.com/ru/post/1265122/


All Articles