Skip to content

Instantly share code, notes, and snippets.

@burtyish
Last active August 29, 2015 14:26
Show Gist options
  • Save burtyish/9b88b8009eb70d8ee74f to your computer and use it in GitHub Desktop.
Save burtyish/9b88b8009eb70d8ee74f to your computer and use it in GitHub Desktop.

The waitFor function wraps a component. This component will be rendered only once all promises in the promises iterable are resolved.

Options:

  • meanwhile: A react node which will be rendered until promises are resolved.
  • error: A react ndoe to be renderd in case any of the promises are rejected.

This is my first attempt at a higher-order component, inspired by Dan Abramov's post.

require 'babel/polyfill'
React = require 'react'
import waitFor from './wait-for.js';
function procrastinate(ms = 0){
const p = new Promise((resolve, reject) => {
window.setTimeout(() => {
console.log(`(${ms}) ding!`);
resolve()
}, ms);
}
);
return p;
}
function waitAndFail(ms = 0){
const p = new Promise((resolve, reject) => {
window.setTimeout(() => {
console.log(`(${ms}) x_x!`);
reject()
}, ms);
}
);
return p;
}
var Starter = React.createClass({
propTypes: {},
getDefaultProps(){
return {
}
},
render() {
return (
<div>
LOADED!
</div>
);
}
});
Starter = waitFor(Starter, [procrastinate(5000), procrastinate(500), procrastinate(3000)],
{
meanwhile: <div>Loading....</div>,
error: <div>FAIL!!! x_x</div>
});
React.render <Starter/>, document.getElementById 'main'
import React from 'react';
function waitFor(Component, promises /* iterable */, options /* object */) {
const WaitFor = React.createClass({
getInitialState() {
return {
ready: false,
failed: false
}
},
componentDidMount(){
Promise.all(promises)
.then(
() => {
this.setState({ready: true});
},
(reason) => {
console.log(`rejected with reason: ${reason}`);
this.setState({failed: true});
}
);
},
render() {
if (this.state.ready) {
return (
<Component {...this.props} />
);
}
if (this.state.failed && options.error) {
return options.error;
}
if (options.meanwhile) {
return options.meanwhile;
}
return null;
}
});
return WaitFor;
}
export default waitFor;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment