So essentially I have a pattern I will like to use throughout my api calls. It's essentially a try catch finally block where I dispatch a series of actions. Instead of copying and pasting this pattern everywhere, I'd like to create a wrapper function where all I pass in are the necessary parameters, api function, and dispatch actions.
My try call block function looks like this:
export function getTokenAPI(username, password) {
return async function action(dispatch) {
try {
dispatch(loadingActions.loadingInProgress(true));
const { data } = await API.authGetToken(username, password);
const { success } = data;
console.log('get token api data', data);
if (success) {
dispatch(setData(data));
dispatch(setTokenSuccess());
} else if (!success) {
const { errorMessage } = data;
throw Error(errorMessage || 'You broke it, not my fault');
}
} catch (e) {
dispatch(errorActions.addError(e.message));
dispatch(errorActions.removeError());
} finally {
dispatch(loadingActions.loadingInProgress(false));
}
};
}
So the wrapper I tried to create looks like this:
function wrapper(apiFunction, dispatchAction) {
return async function action(dispatch) {
try {
dispatch(loadingActions.loadingInProgress(true));
const { data } = await apiFunction(arg1, arg2);
const { success } = data;
if (success) {
dispatch(dispatchAction(data));
} else if (!success) {
const { errorMessage } = data;
throw Error(errorMessage || 'meh');
}
} catch (e) {
dispatch(errorActions.addError(e.message));
dispatch(errorActions.removeError());
} finally {
dispatch(loadingActions.loadingInProgress(false));
}
};
}
With that I can eventually just run
wrapper(apiFunction(username, password), setData)
but I'm getting a TypeError Cannot read property type of undefined. I'm wondering if I'm going about this the right way at all.
Any suggestions or recommendations?