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.
source share