Created
April 18, 2019 01:45
-
-
Save MrJackdaw/d521da613e7754697a252d7f93b880fc to your computer and use it in GitHub Desktop.
React Async Component Loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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