Skip to content

Instantly share code, notes, and snippets.

@MrJackdaw
Created April 18, 2019 01:45
Show Gist options
  • Save MrJackdaw/d521da613e7754697a252d7f93b880fc to your computer and use it in GitHub Desktop.
Save MrJackdaw/d521da613e7754697a252d7f93b880fc to your computer and use it in GitHub Desktop.
React Async Component Loader
import React, { Component } from 'react';
/**
* HOC for asynchronously loading a component dependency.
*
* Use: replace
* import MyComponent from './path/to/my-component';
*
* With:
* const MyComponent = AsyncLoader(() => import('./path/to/my-component'));
*
* Expand as needed
*/
export default function AsyncLoader(importComponent) {
return class AsyncComponent extends Component {
state = { component: null, error: false }
componentDidMount(){
this.mounted = true;
importComponent()
.then(this.onComponentFetched)
.catch(this.onComponentFail);
}
onComponentFetched = componentResponse => {
const component = componentResponse.default;
return this.setState(setError({ component }, false));
}
onComponentFail = () => this.setState(setError({}))
render() {
if (!this.state.component) {
return (this.state.error) ?
(<p>Error loading component</p>) :
(<p>Loading ... </p>)
}
const WrappedComponent = this.state.component;
return <WrappedComponent {...this.props} />
}
}
}
function setError(obj, hasError = true) {
return Object.assign({ }, { ...obj }, { error: hasError });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment