Created
June 7, 2017 05:25
-
-
Save mlrawlings/98c0c97255a1c3a2b9b855648a6b132c to your computer and use it in GitHub Desktop.
Higher Order Component for Handling Promises in React
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
function pend(getPromises, Child) { | |
return class extends Component { | |
constructor(props) { | |
super(props); | |
let promises = getPromises(props); | |
this.state = { pending: promises }; | |
Object.entries(promises).forEach(([name, promise]) => { | |
promise.then( | |
result => { | |
this.setState(state => { | |
let nextState = { [name]: result }; | |
let pending = state.pending; | |
delete pending[name]; | |
if (Object.keys(pending) === 0) { | |
nextState.pending = false; | |
} else { | |
nextState.pending = pending; | |
} | |
return nextState; | |
}); | |
}, | |
error => { | |
this.setState(state => { | |
let rejected = state.rejected || {}; | |
rejected[name] = error; | |
return { rejected }; | |
}); | |
}, | |
); | |
}); | |
} | |
render() { | |
let props = { ...this.props, ...this.state }; | |
return <Child {...props} />; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment