Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react';
- import PropTypes from 'prop-types';
- class DataFetcher extends Component {
- constructor(props) {
- super(props);
- this._activePromises = 0;
- this.result = {};
- this.errors = null;
- this._toBeExecuted = Object.keys(props.loader).length;
- this.checkState = this.checkState.bind(this);
- this.spawn = this.spawn.bind(this);
- this.state = {
- loading: true,
- };
- }
- checkState() {
- if (this._activePromises === 0 && this._toBeExecuted === 0) {
- this.setState({
- loading: false,
- result: { ...this.result },
- errors: this.errors || null,
- });
- }
- }
- spawn(name, fetcher) {
- this._activePromises++;
- this._toBeExecuted--;
- fetcher()
- .then(data => {
- this.result[name] = data;
- this._activePromises--;
- })
- .catch(error => {
- if (!this.errors) this.errors = {};
- this.errors[name] = error;
- this._activePromises--;
- })
- .then(() => {
- this.checkState();
- });
- }
- componentDidMount() {
- const { loader } = this.props;
- Object.keys(loader).map(x => {
- this.spawn(x, loader[x]);
- });
- }
- render() {
- const { result, loading, errors } = this.state;
- const { render, children } = this.props;
- if (typeof render === 'function') {
- return render({ result, loading, errors });
- }
- if (typeof children === 'function') {
- return children({ result, loading, errors });
- }
- }
- }
- DataFetcher.propTypes = {
- loader: PropTypes.object.isRequired,
- render: PropTypes.func,
- children: PropTypes.func,
- };
- export default DataFetcher;
Add Comment
Please, Sign In to add comment