This is a short code snippet from a pet project I used to have fun with five or six months ago. It may not work as I just pasted code from it but I hope it shows the main ideas.
This gist takes as granted you know the documentation of re-frame. It give an example to this part of the documentation: subscribing to external data Poke me if you want help about it.
It suggests an idiomatic way to retrieve data from the outter world within re-frame mindset. The idea is to be pure and enforces the definition of app-db
: single source of truth. A Reagent component should trust it and shouldn't be able to question it.
A component only subscribes to data in the per-definition true
app-db
. Subscriptions and events take care of issuing requests to data from the outter world and inserting it into the db. Such asynchronous insertion results in a update of any component subscribing to this piece of data.
In addition to that, this gist shows some uncommon usages of re-frame interceptors.
In further addition to that, this gist shows a way to debounce data requests to avoid sinking an external database with useless yet costly queries. Warning: debouncing is different from throttling ;-)
For whom cares about purity:
- Component are pure functions. This way to do it ensures it.
- Use Effectful handlers to keep your event handlers pure.
- Purer code is easier to understand.
As a reward for being pure, you can use Figwheel in a much better way
-
Bad way to use Figwheel: each time you modify the code of your unpure component, Figwheel reloads it. Your component issues data requests so data it relies on are wiped and you loose its state. It takes only 10 seconds for you to get back in the same state but you have to do it every single times you change the code of your component. You end up loosing a lot of time.
-
Natural way to use Figwheel: each time you modify the code of a pure component, Figwheel reloads it. Your component subscribes to data which already are in
app-db
so its state is preserved. Perhaps (as shown herein this code) you want to refresh dat in background: this is not a problem since data value itself won't change. As re-frame relies on data value to reload subscription, if data subscribed to doesn't take a new value, no reload will happen.
I'll be very happy to be stumbled upon for more details. However, I no longer want to only work about re-frame and you have to give me time to finish and publish this project as a real POC ;-)