Skip to content

Instantly share code, notes, and snippets.

@jpgorman
Last active April 20, 2018 15:49
Show Gist options
  • Save jpgorman/7cde93e7a416c7182c742f3229f7b20e to your computer and use it in GitHub Desktop.
Save jpgorman/7cde93e7a416c7182c742f3229f7b20e to your computer and use it in GitHub Desktop.
Waiter example
// 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