Skip to content

Instantly share code, notes, and snippets.

@PaquitoSoft
Created November 3, 2018 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaquitoSoft/86ff3c811eb2ba8b725fa738c50c6867 to your computer and use it in GitHub Desktop.
Save PaquitoSoft/86ff3c811eb2ba8b725fa738c50c6867 to your computer and use it in GitHub Desktop.
import React from 'react';
import LoaderContext from '../contexts/loader-context';
export default function withExternalData(WrappedComponent, loader) {
return class extends React.Component {
static contextType = LoaderContext;
constructor(props) {
super(props);
this.state = {
isLoading: false,
externalData: undefined,
error: undefined
};
}
async componentDidMount() {
this.setState({ isLoading: true });
this.context.setIsLoading(true);
try {
const externalData = await loader();
this.setState({
isLoading: false,
externalData
});
this.context.setIsLoading(false);
} catch (error) {
console.warn('Could not load external data:', error);
this.setState({
isLoading: false,
error: error
});
this.context.setIsLoading(false);
}
}
render() {
const props = {
...this.props,
...this.state
};
return (
<WrappedComponent {...props} />
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment