Skip to content

Commit dd1a4db

Browse files
committed
Added AsyncComponent
1 parent 9d39bcb commit dd1a4db

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/AsyncComponent.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import React, { Component } from 'react';
2+
3+
const errorLoading = (err) => console.error('AsyncComponent: Loading failed', err);
4+
const isFunction = (func) => Object.prototype.toString.call(func) === '[object Function]';
5+
6+
export default (loader, { placeholder } = {}) => {
7+
class AsyncComponent extends Component {
8+
constructor() {
9+
super();
10+
11+
this.state = {
12+
component: null
13+
};
14+
this.mounting = true;
15+
}
16+
17+
componentWillMount() {
18+
if (!isFunction(loader)) {
19+
return console.error('AsyncComponent: Loader is not function');
20+
}
21+
22+
loader()
23+
.then((module) => this.mounting && this.setState({ component: module.default }))
24+
.catch(errorLoading);
25+
}
26+
27+
componentWillUnmount() {
28+
this.mounting = true;
29+
}
30+
31+
render() {
32+
if (this.state.component) {
33+
return <this.state.component {...this.props} />
34+
}
35+
36+
return (
37+
placeholder || null
38+
);
39+
}
40+
}
41+
42+
return AsyncComponent;
43+
}

src/index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import AsyncComponent from './AsyncComponent';
2+
3+
export {
4+
AsyncComponent
5+
}

0 commit comments

Comments
 (0)