Created
March 9, 2020 12:22
-
-
Save desphilboy/baf64c3fe94e377628aa216d5210e436 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, { Component } from 'react'; | |
import { getComponentName, isValidFn } from '../utils.js'; | |
export function withInit(init, callInitLogic, inProgressLogic, Spinner) { | |
return BaseComponent => | |
class extends Component { | |
static getDerivedStateFromProps(props, state) { | |
const callInit = !!( | |
callInitLogic && (typeof callInitLogic === 'function' ? callInitLogic(props) : callInitLogic) | |
); | |
const inProgress = !!(isValidFn(inProgressLogic) ? inProgressLogic(props) : inProgressLogic); | |
if (callInit && !inProgress) { | |
if (isValidFn(init)) { | |
init(props); | |
} | |
} | |
if (inProgress || callInit) { | |
if (!state.showSpinner) { | |
return { showSpinner: true }; | |
} | |
} | |
if (!callInit && !inProgress && state.showSpinner) { | |
return { showSpinner: false }; | |
} | |
return null; | |
} | |
static displayName = `withInit(${getComponentName(BaseComponent)})`; | |
constructor(props) { | |
super(props); | |
this.state = { showSpinner: !!Spinner }; | |
} | |
render() { | |
return this.state.showSpinner ? ( | |
<Spinner {...this.state} {...this.props} /> | |
) : ( | |
<BaseComponent {...this.state} {...this.props} /> | |
); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment