Created
May 24, 2015 16:22
-
-
Save rohozhnikoff/9bcd20c98ae53dc597c2 to your computer and use it in GitHub Desktop.
concept to load data before render, in react
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
React.createComponent({ | |
mixins: [ | |
loadPropsMixin | |
], | |
loadProps: { | |
users: api.get('/users') | |
}, | |
}) | |
// loadPropsMixin.js | |
var values = require('lodash/object/values'); | |
var isPlainObject = require('lodash/lang/isPlainObject'); | |
var isFunction = require('lodash/lang/isFunction'); | |
var isEmpty = require('lodash/lang/isEmpty'); | |
var map = require('lodash/collection/map'); | |
var reduce = require('lodash/collection/reduce'); | |
var extend = require('lodash/object/extend'); | |
var Promise = require('promise'); | |
var React = require('react'); | |
module.exports = { | |
renderLoader: function () { | |
return (<span>Loading...</span>); | |
}, | |
componentWillMount: function () { | |
if (!isPlainObject(this.loadProps) || isEmpty(this.loadProps)) { | |
return; | |
} | |
this.isLoaded = false; | |
/* patch .render method */ | |
var originalRender = this.render; | |
this.render = function () { | |
if (this.isLoaded) { | |
return originalRender() | |
} else { | |
return this.renderLoader() | |
} | |
}; | |
/* work with promises */ | |
var promises = values(this.loadProps), | |
keys = Object.keys(this.loadProps); | |
promises = promises.map(function(promise){ | |
if (isFunction(promise)) { | |
return promise.bind(this)(); // sometimes we need create Promise dynamically | |
} else { | |
return promise; | |
} | |
}); | |
Promise.all(promises).then(function (results) { | |
if (!this.isMounted()) { | |
return; | |
} | |
var newProps = reduce(keys, function (memo, key, i) { | |
memo[key] = results[i]; | |
return memo; | |
}, {}); | |
/* todo: find more true-way to set values */ | |
/* and check propTypes as at normal way */ | |
extend(this.props, newProps); | |
this.isLoaded = true; | |
this.forceUpdate(); | |
}.bind(this)); | |
}, | |
componentDidMount: function () { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment