Created
November 27, 2019 22:38
-
-
Save apfzvd/26fb4b819dc23f0ee26a283d44456db1 to your computer and use it in GitHub Desktop.
asyncAction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const createNewBanner = attrs => | |
asyncAction({ | |
type: 'FETCH_USERS', | |
request: () => users.fetch(attrs), | |
success: { | |
callback: (payload, dispatch) => { | |
console.log(payload.data) | |
dispatch({ type: 'RELOAD_USERS' }) | |
}, | |
}, | |
name: 'users teste 123', | |
}); | |
const asyncAction = ({ | |
type, | |
request, | |
success = { callback: null }, | |
fail = { callback: null }, | |
callback = null, | |
suffix = ['PENDING', 'SUCCESS', 'FAIL'], | |
...keys, | |
}) => { | |
if (!type || !request || typeof suffix !== 'object' || suffix.length < 3) { | |
throw new Error('asyncAction: Verificar parâmetros enviados'); | |
} | |
return async dispatch => { | |
dispatch({ | |
type: `${type}_${suffix[0]}`, | |
...keys, | |
}); | |
try { | |
const payload = await request(); | |
dispatch({ | |
type: `${type}_${suffix[1]}`, | |
payload, | |
...keys, | |
}); | |
success.callback && successResponse.callback(payload, dispatch); | |
callback && callback(payload, dispatch); | |
} catch (error) { | |
dispatch({ | |
type: `${type}_${suffix[2]}`, | |
error, | |
...keys, | |
}); | |
fail.callback && failResponse.callback(error, dispatch); | |
callback && callback(error, dispatch); | |
throw new Error(error); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment