Created
February 27, 2016 14:50
-
-
Save AlicanC/93631c650ea599a2f261 to your computer and use it in GitHub Desktop.
A legacy decorator for React components with componentDidMount methods that do asynchronous tasks
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 _ from 'lodash'; | |
export default function asyncComponentDidMount(rejector = 'Component was unmounted.') { | |
return (component) => { | |
const cancelMap = new WeakMap(); | |
const isCancelled = async (promise) => { | |
let cancelled = cancelMap.get(this); | |
if (cancelled) return cancelled; | |
const result = await promise; | |
cancelled = cancelMap.get(this); | |
if (cancelled) return cancelled; | |
return result; | |
}; | |
/* eslint-disable no-param-reassign */ | |
component.prototype.componentDidMount = _.wrap(component.prototype.componentDidMount, | |
function componentDidMountWrapper(func, ...args) { | |
cancelMap.set(this, false); | |
if (typeof func === 'function') { | |
func.apply(this, [isCancelled, ...args]); | |
} | |
} | |
); | |
component.prototype.componentWillUnmount = _.wrap(component.prototype.componentWillUnmount, | |
function componentWillUnmountWrapper(func, ...args) { | |
let rejection; | |
if (typeof rejector === 'function') { | |
rejection = Promise.reject(rejector(this)); | |
} else { | |
rejection = Promise.reject(rejector); | |
} | |
cancelMap.set(this, rejection); | |
if (typeof func === 'function') { | |
func.apply(this, args); | |
} | |
} | |
); | |
/* eslint-enable no-param-reassign */ | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Caveats
You will get unhandled rejections.