Marty.js – A JavaScript library for state management in React applications
martyjs.org
martyjs.org
The beauty of flux + react is, it's so simple and flexible.
I'm developing a fairly complex application with flux + react, (no flux frameworks, just facebook's dispatcher and stores/actions modelled after facebook's flux examples), and it seems I've implemented lots of things in marty.js. I also started using mixins for subscribing views to stores, immutable data in stores (so undo/redo is available without much work), loading data into stores from different sources etc.
I believe, in the following months, a de-facto flux framework will emerge, and marty looks so close to being that framework.
A few tips to fellow developers want to try react and/or flux:
- React is just the view part. Integrating it with other frameworks is easy, and integrating other js libs with react is also easy.
- OTOH, if you want to build a whole complex app with react, use something like flux with it, since there isn't a flexible way to modify the app state from child components with react.
- Immutable data structures really goes well with react + flux. I haven't been able to get the immutability/functional style before, and react + flux really helped with that.
Thanks again for the great tools.
One cautionary note about how easy it is to integrate React with other frameworks: this statement is true as long as the framework in question doesn't touch the DOM (e.g., using Backbone models). But if you try to integrate React with any JS library or framework that mutates the DOM, you should be aware that this will interfere with React's DOM "accounting" and potentially cause lots of problems.
There are certainly ways around this (look into the lesser-used React life cycles), but it's much easier to stick within the React ecosystem for any libraries that manipulate the DOM, or build your DOM manipulations from scratch (easy to do with React). Already, there's a fairly feature complete React Bootstrap library [2]. I've started work on a React charting library, using d3 for path calculations and other utilities (and temporarily for chart axes generation, but library users shouldn't have to worry about any DOM issues) [3]. And I'm sure there are a thousand and one other React view-level component libraries I'm not familiar with, most of which are likely available via NPM.
But I agree that React and the other virtual DOM libraries and frameworks (Ractive, Mercury, Om, etc.) are the next generation approach for client-side views. They not only make DOM manipulations much snappier, but they also make them much easier for the developer.
1. https://github.com/dustingetz/react-cursor
The react-cursor library really introduced cursors based on immutable data for me. I've never used the library, but the idea stuck. Omniscient looks very shiny as well, but it too invasively changes the workings of React for me.
Immutable.js provides a great Immutability library, with a very lightweight cursor implementation on top. You can make a simple object that recursively updates itself with the newest state from the cursor. You have to merge updated states at the keyPath to prevent clobbering from 'synchronous' updates at different cursors.
If you give that object a listen(), a getCurrentState() and a private trigger() method, you are well on your way to a complete store. Reflux offers roughly this model, and adds much needed actions and listening to other stores.
Here's a gist with a tightly coupled (incomplete) example store that emits a cursor, and a React component that listens to the store and updates it:
Thus, you can simplify to something like this: https://gist.github.com/Dashed/707664be1319bb222c7c
-------
Omniscient is still useful in that you can make your own `component` shim using their `shouldComponentUpdate()`.
I think the reflux model doesn't too synergize well with immutable-js's cursors. I found out that reflux with omniscient/immstruct ended up being one more level of indirection. Plus, I didn't need all the features that reflux provided. I even tried a super-light version of reflux.
So I replaced reflux with an augmentation upon immstruct with more useful features (a library I've yet to release). I'm still experimenting with it while investigating a nice isomorphic architecture.
It's worth trying to understand the data structure and why it was used before you dismiss it out of hand. It was a very deliberate choice. There is also a very strong 1:1 mapping between plain old javascript objects and the state data structure you build up with observ, observ-struct and observ-varhash. Serialization and hydration works basically out of the box.
My reaction to the marty stuff is that it's trying to moved towards an architecture that mercury already has out of the box and that you don't have the unnecessary component state stuff the parent comment mentioned.
The component state stuff is probably my biggest gripe with the way react is architected.
For example, when implementing a dropdown menu with react, holding the dropdown menu's open/closed state in the component, and modifying it with onClick events is really convenient.
I do appreciate you taking the time to lay out the advantages, and I was rather flippant.
For me, appealing side of react + flux for me is it's simplicity. Adhere to the few principles of them (one way data flow, no permanent state in components etc.), and you have a scalable architecture in your hands, with little to no magic on the data side.
Haven't used marty yet, and since I've already developed what marty offers on my own app already I don't plan on using it soon, but from what I read in the docs, it doesn't try to do too much, or make too many decisions on your behalf. It offers more structure than a barebones dispatcher, without getting in the way. And in my experience, that is a really efficient and scalable way of building complex apps.
The fact it's got a Chrome extension and what appears to be comprehensive documentation bodes well. I'm currently using reflux because I like its simplicity (no dispatcher and no action creators) but Marty has definitely piqued my interest.
Edit: Question for the author. Any thoughts on isomorphic apps with Marty? Edit2: Answering my own question: https://github.com/jhollingworth/marty/issues/13
var UserState = Marty.createStateMixin({ listenTo: "UserStore", getState: function (UserStore) { return { users: UserStore.getAll() }; } });
A reference: https://www.tildedave.com/2014/11/15/introduction-to-context...
Fluxxor, FYI, bundles all of this in context.flux: https://github.com/BinaryMuse/fluxxor/blob/master/lib/flux_m...
Right now, if I create a Store for a collection of Users and I want to be able to mutate these User objects then I create actions for each CRUD mutation and then plumb that change through to the in-memory object inside my collection as well as persist the change to my server.
But as soon as I click on a specific User and load up a new page for that User, for example, then I need to create an all new Store just for a single User, which has all of the same mutations/actions available to it as the previously-mentioned collection Store (except now I don't need to pass the ID to every action payload).
The best approach I've seen on this topic is in this example's Readme: https://github.com/gaearon/flux-react-router-example
Does this approach make sense/jive with the Marty.js way of handling Stores, State Sources, etc?
Another way is to use a nested immutable data structure (something like immutable.js[1], react-cursor[2]), use only one store, and make all changes on this data structure and pass accordingly.
Even if you don't use immutable.js, I strongly suggest to use immutability with react update[3] or equivalent. Things get way easier that way.
[1]: https://github.com/facebook/immutable-js
I ask because the examples I see for react-cursor, etc typically show data being mutated directly inside the React component without using Actions/Stores/etc. Going this route means we lose the advantages such as a unidirectional data flow & the ability to centralize logic for interacting with a Store around well-defined Actions.
So if we did merge the Flux idea with Cursors, I assume we would keep a single Cursor as the underlying state inside a Store, and then use the traditional Action/ActionCreator model to allow React components/server updates to mutate this Store?
What is the big win here then vs. traditional (non-immutable) Stores (other than performance gains by using === in shouldComponentUpdate)? It seems to me you would still have to make a separate Store for editing a single item vs editing a collection.
We recently went with Reflux[1] for our first big React app after reading about it here[2], and I've been pretty happy with it so far.
The project involved asynchronous requests triggered by the actions, and transforming & aggregating the returned data. Compared to Reflux, Bacon made it very easy to do this by composing small functions that are applied sequentially to a stream of actions.
https://github.com/goatslacker/alt
which looks a bit like reflux in terms of terseness but it adds the ability to have snapshots and rollbacks, isomorphism, and it plays real well with ES6.
There's a few of the flux examples that compare flux to alt in the repo. And there are some good isomorphic examples in here https://github.com/goatslacker/iso/tree/master/examples
I'll be posting a write-up of all this pretty soon.
If you like reflux you'll like alt.
Personally, I've been playing around with Bacon.js (or RxJS) instead of the Flux dispatcher. Using `Bacon.update` in conjunction with Facebook's Immutable.js seems really promising. The outcome is a far more functional approach.
A quick and dirty example: https://gist.github.com/rattrayalex/dee40d86813bcaa9de80
[0] http://blog.hertzen.com/post/102991359167/flux-inspired-reac...
I'm a little worried about finding a good answer to the Flux Dispatcher's elegant `waitFor`, but I have a few ideas that I think could handle that well. I'm also worried about "stream spaghetti", especially having streams defined outside of a central `Actions.js`. I'm not yet sure how to elegantly handle server-syncing, though again, I have a few ideas (and Marty seems to provide some too). Lastly, I don't know the performance characteristics of Bacon or RxJS.
Ultimately, pure-Bacon seems more functional, and I wanted to use something where all the "primitives" (Immutable, Bacon, etc) can be used directly, and are extremely well-supported. I may add a few abstractions (eg; a basic Mixin for event-binding, along the lines of [0]), but would prefer not to have a framework that "does too much" or has much magic, at least until it's very widely-used.
The reason is that I'm coming from a React/Backbone background (see [0]), where the Backbone Model was passed in as a prop, and then also listened-to within the component. So in that context it would make more sense for it to be `props` instead of `state`. In this case, you can't really pass the person object in as props and then listen to it for changes from within the component, since the object is different from the stream "emitting" it. When the emitter and the object are different things, it makes sense that the emitter comes from `props` (or is directly `require()`'d, which may be an anti-pattern?) and the object is set in `state`.
[0] http://www.toptal.com/front-end/simple-data-flow-in-react-ap...
This however forces you to keep all your model logic (computation, transformation, validation and server-communication) in the parent view component. So you'll extract a Model out of it, in which you keep all this data and logic. All the handler methods in the parent component would then call the mutation methods in this model instead of changing the component state directly. But now you need to ensure that the component state is consistent with the model state, for which you hook into the Model's onChange callback in the component's `componentDidMount` method. This means whenever the Model mutates, the component state changes accordingly. For example, if you have a `setPageTitle` method in the Store (that's what we call our Models in Flux), the store would mutate the value when `setPageTitle` is invoked, and call its own `emitChange` method, which triggers the `onChange` callback on the component which was registered during its `componentDidMount`.
See: https://github.com/facebook/flux/blob/master/examples/flux-c.... You use EventEmitter (I prefer EventEmitter3) on the Store to make it an observable. See: https://github.com/facebook/flux/blob/master/examples/flux-c....
The first step in Flux is this: a simple View-Model separation using an EventEmitter store. Apart from the View-Model separation, this lets you share global state between multiple components. (Global state is bad for programmers, but the real world doesn't care. There are instances where you need to share the same data between multiple components and have them all update automatically)
In the ThreadStore example I linked to above, the `emitChange` method is called only through the Dispatcher at the bottom. This is the next step: we do not let any component modify the store values directly. Everything is channeled through a uni-directional dispatcher. The reason to do this is to avoid one Store talking to another Store talking to another, and each of these causing cascading state changes in the components that observe them. So instead of having multiple intertwined paths to the Store, you force the entire application to go through a single-channel dispatcher that process each Action in sequence.
The Actions are simply constants that are available globally to invoke specific behaviour across one or many stores. Each Store watches out for the Actions (a constant pushed into its mesage bus) they are interested in, and calls the appropriate method in its body. You push the Actions into the dispatcher, who is responsible for sending it to each Store.
The dispatcher uses the same EventEmitter observable pattern to bind each Store to the actions they are interested in.
Written in a hurry, but I hope it helps. The flux-chat repo (https://github.com/facebook/flux/blob/master/examples/flux-c...) is a great place to understand the entire pattern.
I've added an isomorphic design to it as a starting point for what will eventually be a fantasy draft application: https://github.com/rblakeley/fifa-heroes
If anyone is interested: https://github.com/kjda/ReactFlux
It's very similar, but I think I like how Actions and subscriptions to actions are handled with it better.
But I may switch to Marty since I'm not far along with the project and the dev tools look super helpful.
I've done it slightly different than you... rather than using `mergeDeep` in `this.setState`, I created some other methods such as `this.setStateAtPath(path, value)` and `this.mergeState` (the latter would use `mergeDeep`)
I'm going to submit a PR to allow for store mixins to be a little more 1st-class: https://github.com/kjda/ReactFlux/issues/4
I'm not very technical, by the way.
For me Marty is the best Flux implementation available right now. When reviewing other frameworks I found them to be either too restrictive by imposing non-flux limitations or the complete opposite by not implementing the flux principles well enough.
What attracted me to fynx was that it uses Facebook's immutable-js[2] for its stores.
It would be nice to get an updated version of this comparison of available flux libraries[3].
1: http://foss-haas.github.io/fynx/ 2: https://github.com/facebook/immutable-js 3: https://reactjsnews.com/the-state-of-flux/
Stores need to be extendable, and the Mixin concept (as used in React Elements) are a very useful way to do it. In this way, one can easily implement Marty's "State Sources" concept. I released a fork of Fluxxor a while ago with Mixin support [1] but it is unlikely to make it until 2.0.
The other nice parts to my eyes are:
State Mixins - sort of a hybrid between Fluxxor's StoreWatchMixin and Fluxxor-autobind [2]
Constants - This is a new one, I like it. Will have to play with it to see if it truly solves any problems; I've found that when I need to know what actions are available, I scan my actions files, simple as that.
Marty seems a little more "batteries included" than the other Flux implementations on the scene. This is a good thing, so long as it is easy to extend. Unfortunately I still don't see Mixins in Marty Stores either. In my opinion they are required for non-trivial apps.
My only pet peeve with Flux is that it does not let me dispatch from within an ongoing dispatch, which is not a huge deal yet because you can just defer the callback to the next event loop, but it's not allowing me to pipeline actions as I thought it should. I have to wait for the stack to empty out before I can dispatch a new action, which sucks. Also, there is no indication as to when a dispatch is over, so I am deferring dispatches by instinct –– or wrapping them in a promise might be the same thing.
I found that no other Flux implementation really helped with fetching data in a Fluxy way. There tended to be a lot of boiler plate code for binding stores to components. Furthermore, there was a lack of tooling for debugging. Marty helps combat these issues by introducing a number of new things:
- Fetch API for fetching data asynchronously without callbacks http://martyjs.org/guides/stores/fetching-data.html - State Mixins for binding stores to views http://martyjs.org/api/state-mixin/ - State sources for syncing state from heterogeneous sources http://martyjs.org/guides/state-sources/index.html - Chrome Developer extension (beta) for visualising the data flow and state of stores http://martyjs.org/devtools/
The Chrome plugin looks very nice, but you can do the same thing with console.log() outputs in your store. It's a nice to have, but not filling a need for me.
by that logic, you don't need a debugger with breakpoints and stack traces either.
i mean... you could use a spoon for driving nails into wood instead of a hammer, too.
Frankly, for small apps, I think you can get 90% of the benefit of Flux by using the pubsub solution of your choice and taking care about only subscribing from top-level components and passing state change down to their children. Immutable cursors are also a nice solution for small apps.
I get that for large teams working on massive code bases, and possibly even for smaller apps, Flux is a big plus. But I'm glad that projects like Marty are working on abstracting out all the boilerplate. Less code for me to worry about.
Do you have any suggestion on the best practice on doing those heavy DOM stuff in React?
I know I can use jQuery for that, but it feels wrong to me.
Also how do you handle integrating React with command based JS library, where your only interface to it is to call mutating functions, such that you cannot blindly rerender the whole things.
Suggestions on these two issues would help me greatly.
> thanks to action types being strings you have a loosely coupled Law of Demeter architecture which is easy to grow without increasing the complexity of the code base.
I don't see the connection between cause and effect, unless this is saying "since everything is in the global state there is no coupling". Seems odd.
I don't mean the whole React library, I mean just "this a the DOM before, here's the change, now patch it" part.
More and more framework and UI library are going to be built around vritual-DOM concept. I don't want integration nightmare of UI-libraries working only on some React-like library.
The examples look for me the same, except some additional functions to declare things.
Some areas that Marty differs in: - State sources: http://martyjs.org/api/state-sources/index.html - Contants are handled more intelligently: http://martyjs.org/api/constants/index.html - Dev tools: http://martyjs.org/devtools/
- Fetch API for fetching data asynchronously without callbacks http://martyjs.org/guides/stores/fetching-data.html - State Mixins for binding stores to views http://martyjs.org/api/state-mixin/ - State sources for syncing state from heterogeneous sources http://martyjs.org/guides/state-sources/index.html - Chrome Developer extension (beta) for visualising the data flow and state of stores http://martyjs.org/devtools/
The integrated data fetching and data flow extension sounds interesting, at the moment i use superagent with the mentioned callbacks and events to visualize (it is not comfortable).
1) actions
2) stores.
In Reflux, a store is effectively just a variable you want your component(s) to be able to access and an action is a function that tells the store what to change about its state. For instance, I might have a CurrentUser store that tracks who the current user is and notifies my Profile component when that changes. I might also have a switchUser action that tells CurrentUser to change its state to user #30. That's all you need to understand to use Reflux.
It's certainly interesting to have data fetching baked into Marty, but it also introduces so many concepts. I think it'd be really helpful for people coming from other libraries if you had a big glossary that says what each thing is and why you felt a need to include it. What's a Marty constant and why is it different than an action creator? What purpose does the dispatcher serve? etc.
You'd have a better time recruiting and training new users with a diagram that shows how all these concepts fit together and why you need so many of them.
You switch between "actions" and "action creators" in this paragraph, which makes it hard to follow:
> Action Creators are where any changes to your applications state starts. Actions are functions that are responsible for coordinating changes to local and remote state. Actions have a type which is a string describing the action (e.g. "UPDATE_USER_EMAIL").
I thought the Action Creator was a function and the Action was the act of invoking it, but that's not clear in the quoted section.
-----
I think your documentation is a bit hard to follow because you're using JavaScript in unexpected ways. For instance, it's a bit weird that your constants are invokable:
updateUserEmail: UserConstants.UPDATE_USER_EMAIL(function (userId, email) {
and I think the line after it mixed constants and action creators:> In the above scenario, UserConstants.UPDATE_USER_EMAIL creates an action creator which, when invoked, will create an action with type UPDATE_USER_EMAIL.
-----
You're missing a ( here:
UserActionCreators.updateUserEmailthis.props.userId, email);
-----In the next example, you use the method name as a key and the constant that triggers it as a value:
handlers: {
updateEmail: UserConstants.UPDATE_USER_EMAIL
},
Since the convention in all the libraries I've seen is to use type as the key and the callback as the value, most developers are going to be immediately tripped up by this unless you call it out in the documentation.-----
Marty has some interesting ideas. Thanks for sharing them, and for taking the time to make a website explaining them.
- What is the equivalent of the global action bus in Flux?
- How do you handle consuming data from multiple rest endpoints?
- Suppose you want to restructure the components in the app into a different hierarchy, how much refactoring is involved?
- Is there any open source example code of an app built this way that is more complex than a simple todo or simple async example? (I think the biggest challenge with these kinds of apps comes at that next tier of complexity... it's trivial to do a clean TODO implementation that doesn't do anything with server data in nearly any framework).
When a component needs data, it subscribes to the relevant stores, and updates itself on data changes.
When you want to mutate the data, you call an action, which in turns mutate the data in the store. Since the components are subscribed to stores, they get the new data automatically.
Stores subscribe to a central dispatcher, listening to all actions. When an action fires, they look the action's data, and mutate their data if it is relevant to them.
The data flow is action-> dispatcher-> store -> component -> action.
When you want to get data from a rest endpoint, you fire an action from the component. The action fetches the data, and pushes it to dispatcher.
Flux is an architecture.
I used BaconJS and I found that my overall page event and data flow ended up being reactive spaghetti. Architecture is not my strong suit. One of the great things about flux is having extremely strong conventions about where everything goes:
- All interactions are through actions.
- All state is in stores.
- No mutable state in the actual UI.
- etc.
What's your overall dataflow architecture look like using RxJS or BaconJS?
I found using BaconJS much nicer if I needed to transform data from asynchronous requests because you end up with a much more functional approach.