Skip to content

Instantly share code, notes, and snippets.

@mstudio
Created October 2, 2019 20:39
Show Gist options
  • Save mstudio/b6f8ee3c4a4cecd08f01d83ed3a7e33b to your computer and use it in GitHub Desktop.
Save mstudio/b6f8ee3c4a4cecd08f01d83ed3a7e33b to your computer and use it in GitHub Desktop.
React HOC to load data and show Carbon v10 loader
/**
* withData HOC - loads any data as Promise.all, shows loading icon and passes data along via props to children
*/
import React, { Component } from 'react';
import { Loading } from 'carbon-components-react';
import ErrorModal from '../ErrorModal/ErrorModal';
import RequestUtils from '../../utilities/RequestUtils';
/**
* @param {*} WrappedComponent Child React component
* @param {Array} source in form `[{ key: 'string', url: 'string' }, ... ]`
*/
const withData = (WrappedComponent, source) => {
class HOC extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
this.loadData();
}
loadData() {
const promises = source.map(({ key, url }) => (
RequestUtils.request(url, 'GET')
.then(({ results }) => {
this.setState({
[key]: results
});
}).catch((e) => {
this.showError(`"${url}" ${e.message}`);
throw new Error(`"${url}" ${e.message}`);
})
));
Promise.all(promises).then((v1, v2, v3) => {
console.log('ALL', v1, v2, v3);
this.loadingComplete();
}).catch((e) => {
console.log('error here', e);
});
}
loadingComplete() {
console.log('loading complete');
this.setState({
loading: false,
error: null
});
}
showError(message, e) {
console.log('ERROR', message, e);
this.setState({
loading: false,
error: message
});
}
render() {
console.log('here is state data', this.state.data);
if (this.state.loading) {
return <Loading />;
}
if (this.state.error) {
return <ErrorModal errorMessage={this.state.error} />;
}
return <WrappedComponent {...this.state} />;
}
}
return HOC;
};
export default withData;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment