Created
March 14, 2017 13:47
-
-
Save novykh/21b607043e7a1642f96775f54f20a4eb to your computer and use it in GitHub Desktop.
Higher order component for handling data fetching and loader till it's done - required props are `isDataLoaded` [boolean] and `dispatchGetData` [function that changes isDataLoaded when done in store]
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, {Component} from 'react'; | |
import Loader from '../shared/loader'; | |
const getDisplayName = component => component.displayName || component.name || 'Component'; | |
const Loader = ({message}) => { | |
return ( | |
<div className='bullets-loader'> | |
<div className='bounce1' /> | |
<div className='bounce2' /> | |
<div className='bounce3' /> | |
<span className='bullets-loader__msg'>{message || 'Please wait...'}</span> | |
</div> | |
); | |
}; | |
export default function dataLoader(WrappedComponent) { | |
class Wrapper extends Component { | |
componentDidMount() { | |
this.getDataIfNeeded(true); | |
} | |
componentWillReceiveProps(nextProps) { | |
if (!nextProps.isDataLoaded && nextProps.isDataLoaded !== this.props.isDataLoaded) { | |
this.getDataIfNeeded(!nextProps.isDataLoaded); | |
} | |
} | |
getDataIfNeeded(force = false) { | |
const { | |
isDataLoaded, | |
dispatchGetData | |
} = this.props; | |
if (typeof dispatchGetData !== 'function') { | |
return; | |
} | |
if (force || !isDataLoaded) { | |
dispatchGetData(); | |
} | |
} | |
render() { | |
const { | |
isDataLoaded = true, | |
loadingMessage | |
} = this.props; | |
if (!isDataLoaded) { | |
return <Loader message={loadingMessage} />; | |
} | |
return <WrappedComponent {...this.props} />; | |
} | |
} | |
Wrapper.displayName = `LoaderHOC(${getDisplayName(WrappedComponent)})`; | |
return Wrapper; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment