Skip to content

Instantly share code, notes, and snippets.

@Jaredk3nt
Created October 2, 2018 19:46
Show Gist options
  • Select an option

  • Save Jaredk3nt/4d4f79094e213cc5c4add2706c7828d9 to your computer and use it in GitHub Desktop.

Select an option

Save Jaredk3nt/4d4f79094e213cc5c4add2706c7828d9 to your computer and use it in GitHub Desktop.
Http handler written using Reacts context API
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