Created
August 15, 2020 18:36
-
-
Save calderaro/edcaabd41c03b3532eba202b0af439b2 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
import React from 'react'; | |
export interface AsyncHandlerProps<T> { | |
handler: () => Promise<T>; | |
children(res: { | |
state: State<T>; | |
execute: () => Promise<void>; | |
}): React.ReactNode; | |
} | |
export interface State<T> { | |
status: 'init' | 'executing' | 'executed' | 'failure'; | |
data: T | null; | |
error: Error | null; | |
} | |
class AsyncHandler<T> extends React.Component<AsyncHandlerProps<T>, State<T>> { | |
constructor(props: AsyncHandlerProps<T>) { | |
super(props); | |
this.state = { | |
status: 'init', | |
data: null, | |
error: null | |
}; | |
} | |
execute = async () => { | |
try { | |
this.setState({status: 'executing'}); | |
const data = await this.props.handler(); | |
this.setState({status: 'executed', data}); | |
} catch (error) { | |
this.setState({status: 'failure', error}); | |
} | |
}; | |
render() { | |
return this.props.children?.({state: this.state, execute: this.execute}); | |
} | |
} | |
export default AsyncHandler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment