Skip to content

Instantly share code, notes, and snippets.

@Jaredk3nt
Last active October 2, 2018 20:16
Show Gist options
  • Select an option

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

Select an option

Save Jaredk3nt/eb3880200249bb35c9ef32871f4f9d9d to your computer and use it in GitHub Desktop.
A simple HOC for handling http requests
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