So, I have these functions:
const myFunc1 = () => async (dispatch, getState) => {
if (await dispatch(isSessionExpired())) return;
const authToken = getAuthToken(getState());
if(!authToken){
dispatch(statuses.myFunc1Error());
return;
}
//do something
}
const myFunc2 = () => async (dispatch, getState) => {
if (await dispatch(isSessionExpired())) return;
const authToken = getAuthToken(getState());
if(!authToken){
dispatch(statuses.myFunc2Error());
return;
}
//do something
}
const myFunc3 = () => async (dispatch, getState) => {
if (await dispatch(isSessionExpired())) return;
const authToken = getAuthToken(getState());
if(!authToken){
dispatch(statuses.myFunc3Error());
return;
}
//do something
}
As you can see, there's a lot of repeated code, what's the best way to refactor this? I though doing something like this:
const creatorChecks = async (dispatch, getState, actionName) => {
if (await dispatch(isSessionExpired())) return false;
const authToken = getAuthToken(getState());
if(!authToken){
dispatch(statuses[`${actionName}Error`]());
return false;
}
return true;
}
and then...
const myFunc1 = () => async (dispatch, getState) => {
if(!await creatorChecks(dispatch, getState, 'myFunc1')) return;
// the code...
}
const myFunc2 = () => async (dispatch, getState) => {
if(!await creatorChecks(dispatch, getState, 'myFunc2')) return;
// the code...
}
const myFunc3 = () => async (dispatch, getState) => {
if(!await creatorChecks(dispatch, getState, 'myFunc3')) return;
// the code...
}
But maybe there's a better way...