Second, we believe that [FRP] is a honking great idea. You might be tempted to see
reagent as simply another of the React warappers (a sibling to [OM] and [quiescent](https://github.com/levand/quiescent)). But I think you only really "get"
Reagent when you view it as an [FRP] library. To put that another way, we think
You'll also be designing a data structure to represent the app state, and probably writting a [herbet schema](https://github.com/miner/herbert) for it.
Along the way, I'll be using [reagent] at an intermediate to advanced level. This is not an introduction to reagent tutorial, so you need to have done one of those before getting here. Try
[the offical intro](http://reagent-project.github.io/) or
[this](https://github.com/jonase/reagent-tutorial) or [this](http://yogthos.net/posts/2014-07-15-Building-Single-Page-Apps-with-Reagent.html).
<blockquoteclass="twitter-tweet"lang="en"><p>Well-formed Data at rest is as close to perfection in programming as it gets. All the crap that had to happen to put it there however...</p>— Fogus (@fogus) <ahref="https://twitter.com/fogus/status/454582953067438080">April 11, 2014</a></blockquote>
You'd happily put all your well formed data into Postgres or mysql. But within a running application (in memory), it is different. If you have a background in OO, this data-in-one-place is a
does have to be a "reactive datastore" (one that can tell you when it has changed). In fact, `app-db` doesn't have to be a single atom either -- the pattern allows for as many as you like, although our implementation assumes one.
##### Benifits Arising From This Approach
I'm going to quote verbatum from Elm's website:
1. There is a single source of truth. Traditional approaches force you to write a decent amount of custom and error prone code to synchronize state between many different stateful components. (The state of this widget needs to be synced with the application state, which needs to be synced with some other widget, etc.) By placing all of your state in one location, you eliminate an entire class of bugs in which two components get into inconsistent states. We also think you will end up writing much less code. That has been our observation in Elm so far.
2. Save and Undo become quite easy. Many applications would benefit from the ability to save all application state and send it off to the server so it can be reloaded at some later date. This is extremely difficult when your application state is spread all over the place and potentially tied to objects that cannot be serialized. With a central store, this becomes very simple. Many applications would also benefit from the ability to easily undo user's actions. For example, a painting app is better with Undo. Since everything is immutable in Elm, this is also very easy. Saving past states is trivial, and you will automatically get pretty good sharing guarantees to keep the size of the snapshots down.
Reagent provides a `ratom` (reagent atom) and a `reaction`. These are **two key building blocks**.
`ratoms` are like normal ClojureScript atoms. You can `swap!` and `reset!` them, `watch` them, etc. To put it another way, a ratom is a value that changes over time. A ratom is an FRP [Signal](http://elm-lang.org/learn/What-is-FRP.elm).
`reaction` acts a bit like a function. Its a macro which wraps some `computation` (some block of code) and returns a `ratom` containing the result of that `computation`.
A `reaction` will automatically rerun its `computation` whenever any of these dereferenced ratoms change.
So, the ratom returned by a `reaction` is itself a Signal. Its value will change over time as its input Signals (ratoms) change. You end up with a Signal graph. (Our graph will be without cycles).
You'll notice that our component is a regular clojure function, nothing special. In this case, it takes no parameters and it returns a clojurescript vector (hiccup).
Now, we're now going to introduce `reaction` into this mix. On the one hand, I'm complicating things by doing this, because reagent allows you to be ignorant of the mechanicas I'm about to show you. It invisibly wraps your components in a `reaction` allowing you to be blissfully ignorant of how the magic happens.
On the other hand, it is useful to understand exactly how the Signal graph is wired. AND, in a minute, when we get to subscriptions, we ourselves will be actively using `reaction`, so we might as well bite the bullet here and now ... and, anyway, it is easy ...
So, as `n` changes value over time (it is a Signal), the output of the computation `(greet n)` changes, and so too the value in `hiccup-ratom` changes (it is a Signal).
1. reagent re-runs `reactions` (re-computations) via requestAnnimationFrame. So a recomputation happens about 16ms after the need for it is detected, or after the current thread of processing finishes, whichever is the greater. So if you are in a bREPL and yourun the lines of code above one after the other too quickly, you might not see the re-computation done immediately after `n` gets reset!, because the annimationFrame hasn't run (yet). You could add a `(reagent.core/flush)` after the reset! to force re-computation to happen straight away.
2.`reaction` doesn't actually return a `ratom`. But it returns something that has ratom-nature, so we'll happily continue believing it is a ratom and no harm will come to us.
- you have the full power of ClojureScript available to you (generating a clojure datastructure). The downside is that these are not "designer friendly" HTML templates.
But, just to be clear, we don't have to bother ourselves with most of the pipeline. We just write the `components` part (pure functions) and Reagent/React looks after the rest.
As the app developer, your job is to write and register one or more "subscription handlers" (functions that do a query). Your subscription functions must return a value that changes over time (Signal). Ie. they'll be returning a reaction (ratom).
First, note this is a form-2 `component` (there are 3 forms). Perviously above, we've used the simplest, form-1 components (no setup was required, just render). With form-2, there's a function returning a function:
- the returned function is the render fucntion. Behind the scenes, reagent will wrap this render fucntion in a `reaction` to make it produce new hiccup when its inputs change. In our case, that means it will rerun every time `name-ratom` changes.
- the outer function is a setup function, called once to initialise the component. Notice the use of 'subscribe' with the parameter `:name-query`. That creates a Signal through which new values are supplied over time.
There is only one subscribe function. We must register our `handlers` with it.
The first element in the vector (`query-id`) identifies the query and the other elements are optional, query parameters. With a traditional database a query might be:
**Note**: `components` tend to be organised into a heirarchy, often with data flowing from parent to child via paramters. So not every component needs a subscription.
**Rule**: subscripitons can only be used in form-2 components and the subscription must be in the outer setup function and not in the inner render function. So the following is **wrong** (compare to the correct version above)
Imagine our `app-db` contains some `items` (a vector of maps). And imagine that we must display these items sorted by one of their attributes attribute. We could write this query-handler:
There's a bit going on in that `let`, most of it highly contrived, just so I can show off chained reactions. Okay, okay. All I wanted was an excuse to use the phrase chained reactions.
In reality, the approach taken above is inefficient. Every time `app-db` changes, the `:sorted-items` query is going to be re-run and its going to re-sort items. But items might not have changed since last time. Some other part of app-db may have changed. We don't want to re-sort items each time something unrelated changes.
We can fix that up:
```
(register
:sorted-items ;; the query id
(fn [db [_ sort-kw] ;; sort-kw is a ratom containing the attribute to sort on
Be aware that the second reaction will only be triggered if `items` does not test `identical?` to the previous value. **Yes, that sort of optimiation is built into chain `reactions`.** Which means the component render fucntion (which is wrapped in another reaction) won't rerun if app-db changes, unless items changes. Now we're very efficienct.
If I were doing this for real (rather than just demoing posibilites), I'd probably create a simple subscription for items (unsorted), and then do the sort in the component itself (as a reaction, similar to how 'num' is done in the example above). After all, it is the component which needs to show sorted. It can contain the sorting, which might involve the
Summary:
- you can chain reactions
- reagent will eliminate unnecessary Signal propogation via `identical?` checks (not equality checks!). This is the nice by product of working with immutable datastructures.
### The 2nd Flow
At the top, I said that re-frame had two data flows.
The data flow from `app-db` to the DOM is the first half of the story. We now need to consider the 2nd part of the story: the flow in the opposite direction.
While the first flow has FRP-nature. The 2nd flow does not (although some feel it should).
When I think about these two flows, I imagine [one of those school diagrams](http://thumbnails-visually.netdna-ssl.com/water-cycle_521f29b8b6271_w1500.png) showing the water cycle. Rivers taking water down to the oceans, and evaporation/clouds taking water back over the mountains to fall again as rain. And repeat.
mutate app state (in `app-db`), or requrest more data from the server, or POST somewhere and wait for a response, etc. In fact, all these actions will ultimately result in changes to the `app-db`.
that means the `app-db` will change. After all, it **is** the state. And the DOM presented to the user is a function of that state. So that tends to be the cycle: DOM events dispatch, handler mange them, which cause `app-db` changes, which then cause a rerender, and the users sees something different. That's our water cycle.
**Rule**: `components` are as passive as possible when it comes to handling events. Do the minimum. On the other hand, `components` can be as complex as needed when it comes to creating the visuals.
Almost all event handlers mutate `app-db` in some way. Adding an item here, or deleting that one there. So often CRUD, but sometimes much more. Sometimes with async results.
re-frame passes to an event handler two paramters: the current state of `app-db` plus the event, and the job of a handler to to return a modified version of the state (which re-frame will then put back into the `app-db`). XXX currently not true but it will be shortly.
Above, I commented that collectievly handler represent the control layer of the application.
A big part of what they do is to manage state transitions. The application is in state X, and event Y arrives, so the handler for Y was to move the app to state Z.
Although I've done nothing to try and implement it, this is obviously fertile territory for using [statechars](http://www.amazon.com/Constructing-User-Interface-Statecharts-Horrocks/dp/0201342782).
- all events are handled via a call to `dispatch`. GUI events, async HTTP events, everything.
- a handler can't dispatch. (unless the 2nd one happens is anyc, whcih means it doesn't really happen within the original). XXX with a little bit of work, this rule could be relaxed, but only if the nested dispatch is regarded as happening async. But is it a good idea or necessary?