Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement