Skip to content

Instantly share code, notes, and snippets.

@desphilboy
Created March 9, 2020 12:22
Show Gist options
  • Save desphilboy/baf64c3fe94e377628aa216d5210e436 to your computer and use it in GitHub Desktop.
Save desphilboy/baf64c3fe94e377628aa216d5210e436 to your computer and use it in GitHub Desktop.
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