Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Created April 24, 2014 12:48
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simenbrekken/11253438 to your computer and use it in GitHub Desktop.
Save simenbrekken/11253438 to your computer and use it in GitHub Desktop.
Manipulating React immutable stores with context
var Application = React.createClass({
childContextTypes: {
createProduct: React.PropTypes.func
},
getChildContext: function() {
return {
createProduct: this.createProduct
}
},
componentWillMount: function() {
this.productStore = new ProductStore(this.props.apiUrl)
},
createProduct: function(name, variants) {
return this.productStore.create(name, variants)
}
})
var ProductStore = function(baseUrl, products) {
this.baseUrl = baseUrl + '/products'
this.products = products ? immutable(products) : immutable()
}
// POST /products
ProductStore.prototype.create = function(name, variants) {
return request.post(this.baseUrl, {
name: name,
variants: variants
}).then(function(data) {
return data.id
})
}
var CreateProduct = React.createClass({
contextTypes: {
createProduct: React.PropTypes.func
},
onCreateProduct: function() {
this.context.createProduct().then(function(id) {
console.log(id)
})
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment