Last active
October 2, 2018 20:16
-
-
Save Jaredk3nt/eb3880200249bb35c9ef32871f4f9d9d to your computer and use it in GitHub Desktop.
A simple HOC for handling http requests
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
| class HttpProvider extends Component { | |
| state = { | |
| isLoading: false, | |
| data: [] | |
| } | |
| // Fetch initial data on mount | |
| async componentDidMount() { | |
| await this.updateData(); | |
| } | |
| // HOF for adding loading to async function | |
| withLoading = async (fn) => { | |
| return (body = {}) => { | |
| this.setState(() => ({ isLoading: true })); | |
| await fn(body); | |
| this.setState(() => ({ isLoading: false })); | |
| }; | |
| } | |
| // Get data | |
| updateData = this.withLoading(async () => { | |
| const data = await someHttpCall(); | |
| this.setState(() => ({ data })); | |
| }) | |
| // Inject state and exposed functions to children as props | |
| render() { | |
| return ( | |
| <> | |
| { | |
| React.Children.map(this.props.children, (child) => | |
| React.cloneElement(child, { | |
| ...this.state, | |
| updateData: this.updateData | |
| }) | |
| ) | |
| } | |
| </> | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment