Last active
November 3, 2018 15:36
-
-
Save PaquitoSoft/84b372450dc2e417116cfe18e75f5d02 to your computer and use it in GitHub Desktop.
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 from 'react'; | |
import { func } from 'prop-types'; | |
import LoaderContext from '../contexts/loader-context'; | |
class ExternalDataLoader extends React.Component { | |
static contextType = LoaderContext; | |
constructor(props) { | |
super(props); | |
this.state = { | |
isLoading: false, | |
externalData: undefined, | |
error: undefined | |
}; | |
} | |
async componentDidMount() { | |
this.setState({ isLoading: true }); | |
this.context.setIsLoading(true); | |
try { | |
const externalData = await this.props.loader(); | |
this.setState({ | |
isLoading: false, | |
externalData | |
}); | |
this.context.setIsLoading(false); | |
} catch (error) { | |
console.warn('Could not load external data:', error); | |
this.setState({ | |
isLoading: false, | |
error: error | |
}); | |
this.context.setIsLoading(false); | |
} | |
} | |
render() { | |
return ( | |
<div>{this.props.children(this.state)}</div> | |
); | |
} | |
} | |
ExternalDataLoader.propTypes = { | |
children: func.isRequired, | |
loader: func.isRequired | |
}; | |
export default ExternalDataLoader; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment