Created
October 2, 2018 19:46
-
-
Save Jaredk3nt/4d4f79094e213cc5c4add2706c7828d9 to your computer and use it in GitHub Desktop.
Http handler written using Reacts context API
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
| const DEFAULT = { | |
| data: [], | |
| isLoading: false | |
| } | |
| const { Provider, Consumer } = React.createContext({ ...DEFAULT }); | |
| class HttpProvider extends Component { | |
| state = { ...DEFAULT }; | |
| async componentDidMount() { | |
| await this.updateData(); | |
| } | |
| withLoading = async (fn, body = {}) => { | |
| this.setState(() => ({ isLoading: true })); | |
| const res = await fn(body); | |
| this.setState(() => ({ isLoading: false })); | |
| return res; | |
| } | |
| updateData = async () => { | |
| const data = await this.withLoading(someHttpCall()); | |
| this.setState(() => ({ data })); | |
| } | |
| render() { | |
| const { children } = this.props; | |
| return ( | |
| <Provider value={{ | |
| ...this.state, | |
| updateData: this.updateData | |
| }}> | |
| {children} | |
| </Provider> | |
| ) | |
| } | |
| } | |
| const HttpConsumer = ({}) => { | |
| return ( | |
| <Consumer> | |
| { | |
| (context) => React.Children.map(this.props.children, (child) => | |
| React.cloneElement(child, { ...context }) | |
| ) | |
| } | |
| </Consumer> | |
| ) | |
| } | |
| export { | |
| HttpProvider, | |
| HttpConsumer | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment