Skip to content

Instantly share code, notes, and snippets.

@vslinko
Created April 2, 2016 18:22
Show Gist options
  • Save vslinko/812efe0b1cec3ce06857ce6b269653f3 to your computer and use it in GitHub Desktop.
Save vslinko/812efe0b1cec3ce06857ce6b269653f3 to your computer and use it in GitHub Desktop.
function loadingIndicator() {
return Component => {
return class LodingIndicator extends React.Container {
// static displayName =
constructor() {
super();
this.state = {
counters: {},
};
}
inc(key) {
this.setState({
counters: Object.assign({}, this.state.counters, {
[key]: (this.state.counters[key] || 0) + 1,
}),
});
}
dec(key) {
this.setState({
counters: Object.assign({}, this.state.counters, {
[key]: this.state.counters[key] - 1,
}),
});
}
async run(key, cb) {
this.inc(key);
try {
await cb();
this.dec(key);
} catch {
this.dec(key);
}
}
render() {
const loading = Object.keys(this.state.counters)
.reduce((acc, key) => {
acc[key] = this.state.counters[key] > 0;
return acc;
}, {});
return (
<Component
{...this.props}
loading={loading}
run={(key, cb) => this.run(key, cb)}
/>
);
}
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment