Created
July 14, 2018 13:45
-
-
Save jasonrhodes/4bae008ff2051a7c0f90d4270c256ec7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// these examples use thunks but the problem applies to most other redux async strategies | |
// action creator 1: get user | |
const getUser = async (id) => (dispatch) => { | |
dispatch({ type: 'GET_USER_PENDING', payload: id }) | |
try { | |
const result = await doAsyncThing(id) | |
return dispatch({ type: 'GET_USER_SUCCESS', payload: result }) | |
} catch (error) { | |
return dispatch({ type: 'GET_USER_FAILED', payload: error }) | |
// QUESTION: re-throw error here or not??? | |
} | |
} | |
// action creator 2: update something with user data | |
const updateThing = async (userData) => (dispatch) => { | |
dispatch({ type: 'UPDATE_SOMETHING_PENDING' }) | |
try { | |
await doAsyncThing(userData) | |
return dispatch({ type: 'UPDATE_SOMETHING_SUCCESS', payload: userData }) | |
} catch (error) { | |
return dispatch({ type: 'UPDATE_SOMETHING_FAILED', payload: error }) | |
} | |
} | |
// combo action creator, first get user then update thing | |
const getUserAndUpdateThing = async (id) => (dispatch) => { | |
try { | |
const userData = await getUser(id) | |
await updateThing(userData) | |
} catch (error) { | |
// if we don't re-throw in the above action creators, we would never get here | |
// and we would ALWAYS call updateThing even if the getUser call failed | |
// | |
// if we DO re-throw, we have to re-throw in ALL action creators (probably in an abstraction) | |
// which means your app will be filled with Unhandled Promise Rejection warnings unless you | |
// wrap EVERYTHING with dummy catches, see below | |
} | |
} | |
// if we re-throw in action creators to allow proper promise chaining, | |
// every action creator call has to look like this: | |
componentDidMount() { | |
this.props.getUser(this.props.id).catch(() => { | |
// ignore error, handled through redux actions | |
}) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment