Created
November 3, 2018 15:22
-
-
Save PaquitoSoft/86ff3c811eb2ba8b725fa738c50c6867 to your computer and use it in GitHub Desktop.
This file contains 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 LoaderContext from '../contexts/loader-context'; | |
export default function withExternalData(WrappedComponent, loader) { | |
return class 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 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() { | |
const props = { | |
...this.props, | |
...this.state | |
}; | |
return ( | |
<WrappedComponent {...props} /> | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment