1.0.0 • Published 6 years ago

@elricb/webpack-promise v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
6 years ago

webpack-promise

about

Delayed Promise consumption. Ensures thrown errors do not break processing.

E.G.

import React from 'react';
import WebpackPromise from 'webpack-promise';

class UsePromise extends React.Component {
    constructor(props) {
        super(props);

        // with async operations, you have to ensure the component
        // hasn't unmounted before Promise finishes
        this.active = true;
    }
    componentDidUpdate() {
        this.loadComponent();
    }
    componentDidMount() {
        this.loadComponent();
    }
    componentWillUnmount() {
        this.active = false;
    }
    loadComponent() {
        this.props.component
            .then(Component => this.active && this.setState({ Component }))
            .catch(err => console.error(err));
    }
    render() {
        let { Component } = this.state;

        if (!Component) {
            return null;
        }

        return <Component>;
    }
}

const SetPromise = (props) => (
    <UsePromise
        component={new WebpackPromise(System.import('./' + props.path + '/index.jsx'))}
    />
);

E.G. ID

import React from 'react';
import NotFound from 'component/NotFound';
import WebpackPromise from 'webpack-promise';

class UsePromise extends React.Component {
    constructor(props) {
        super(props);
        this.localPromise = new WebpackPromise();

        // with async operations, you have to ensure the component
        // hasn't unmounted before Promise finishes
        this.active = true;
    }
    componentDidUpdate() {
        this.loadComponent();
    }
    componentDidMount() {
        this.loadComponent();
    }
    componentWillUnmount() {
        this.active = false;
    }
    localComponent() {
        this.localPromise
            .promise(import('./' + wildcard + '/index.jsx'))
            .id(wildcard, id => this.setState({ Component: null }))
            .then(Component => this.setState({ Component }))
            .catch(error => console.error(error));
    }
    loadComponent() {
        this.props.component.id(
            this.props.path,
            () => this.setState({ Component: null })
        )
            .then(Component => this.active && this.setState({ Component }))
            .catch(() => this.setState({ Component: NotFound }));
    }
    render() {
        let { Component } = this.state;

        if (!Component) {
            return null;
        }

        return <Component>;
    }
}

const SetPromise = (props) => (
    <UsePromise
        path={props.path}
        component={new WebpackPromise(System.import('./' + props.path + '/index.jsx'))}
    />
);