Last active
April 20, 2018 15:49
-
-
Save jpgorman/7cde93e7a416c7182c742f3229f7b20e to your computer and use it in GitHub Desktop.
Waiter example
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
// AsyncComponent.js | |
function mapStateToProps(state: IState) { | |
return { | |
data: waitForData(), | |
} | |
} | |
const AsynCompoment = connect(mapStateToProps)(({ data }) => <div>{console.log(data)}</div>) | |
// store.js | |
const waitForData = createWaiter(store, (state) => state.data) | |
// create-waiter.js | |
const createWaiter = (store, stateSelector) => () => { | |
const state = stateSelector(store.getState()) | |
/* | |
as this method is called each time we mount our | |
compoment we need to return early when | |
our data has loaded | |
*/ | |
if (!state.isLoading) { | |
if (state.error != null) { | |
throw state.error | |
} | |
return state | |
} | |
/* | |
if our data isn't ready then we can throw our | |
promise to kick us into the loading state | |
*/ | |
throw new Promise((resolve, reject) => { | |
const unsubscribe = store.subscribe(() => { | |
const state = stateSelector(store.getState()) | |
// resolve when our data has loaded or throw an Error | |
if (!state.isLoading) { | |
if (state.error != null) { | |
unsubscribe() | |
return reject() | |
} | |
unsubscribe() | |
return resolve() | |
} | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment