Skip to content

Instantly share code, notes, and snippets.

@mikaelbr
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikaelbr/72571151ca0d96aff867 to your computer and use it in GitHub Desktop.
Save mikaelbr/72571151ca0d96aff867 to your computer and use it in GitHub Desktop.
Using Immutable for top-down rendering
var Immutable = require('immutable'),
React = require('react'),
component = require('omniscient');
var data = Immutable.fromJS({
title: 'My list',
items: [ 'one', 'two', 'three' ]
});
var EditMixin = {
changeText: function onChange (e) {
// Having access to value through cursors
this.props.cursor.update(function () {
return 'Swapped text!';
});
// or even something like:
// actions.doText(this.props.cursor);
}
};
var Item = component(EditMixin, function (cursor) {
// With Immutable 2.4.0
// return d.span({ onClick: this.changeText }, Immutable.unCursor(cursor));
return React.DOM.li({ onClick: this.changeText }, cursor.deref());
});
var List = component(function (cursor) {
return React.DOM.div({},
React.DOM.h1({}, cursor.get('title')),
React.DOM.ul({},
cursor.cursor('items').map(function (v, key, itemsCursor) {
return Item('item-' + key, itemsCursor.cursor(key));
}).toArray()
)
);
});
var body = document.querySelector('body');
render();
function render () {
var cursor = data.cursor(function (newData) {
data = newData;
render();
});
React.renderComponent(List(cursor), body);
}
@leebyron
Copy link

You could update this example by changing your data structure to be:

items: [ {name: 'one'}, {name: 'two'}, {name: 'three'} ]

And then referencing cursor.get('name') and cursor.update('name', v => v)

And on line 32, you can replace itemsCursor.cursor(key) with itemsCursor.get(key) -- that also returns a wrapped cursor value for Immutable collections.

@mikaelbr
Copy link
Author

Thanks for your comment! This would how ever alter my data structure. Trivial in this contrived case, but can in larger structures not be as trivial. I've updated the original issue with my response: immutable-js/immutable-js#97 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment