Skip to content

Instantly share code, notes, and snippets.

@eneroth
Last active October 16, 2019 17:23
Show Gist options
  • Save eneroth/afe3f0fd9b4cadc1c684e83aec334383 to your computer and use it in GitHub Desktop.
Save eneroth/afe3f0fd9b4cadc1c684e83aec334383 to your computer and use it in GitHub Desktop.
Custom add-watch function for Fulcro 3. Triggers a function based on a query.
(ns poc.util.app
(:require [com.fulcrologic.fulcro.algorithms.denormalize :as denormalize]))
(defn add-query-watch
"Takes at minimum an app, a registry-key, a query, a starting-entity, and a function.
Optionally takes an an options map as last argument.
Attaches a watch to the app state, using registry-key as the key for the watch.
When the queried state changes, triggers function f.
f receives an environment map, the old (denormalized) state, and the new (denormalized)
state of the query as first, second, and third arguments respectively.
The environment map contains the keys :app, :registry-key, :query, and :starting-entity, as
per the arguments supplied to this function.
If the options map contains key :trigger-on-init, with value set to true, will
trigger function f with the environment map, nil and the initial (denormalized) query state
upon creating the watch."
[app registry-key query starting-entity f & [opts]]
(let [app-state-atom (:com.fulcrologic.fulcro.application/state-atom app)
current-denormalized-state (denormalize/db->tree query starting-entity @app-state-atom)
memoization-atom (atom current-denormalized-state)
env {:app app
:registry-key registry-key
:query query
:starting-entity starting-entity}]
(when (true? (:trigger-on-init opts))
(f env nil current-denormalized-state))
(add-watch app-state-atom registry-key
(fn [_ _ _ new-state]
(let [old-denormalized @memoization-atom
new-denormalized (denormalize/db->tree query starting-entity new-state)]
(when (not= old-denormalized new-denormalized)
(reset! memoization-atom new-denormalized)
(f env old-denormalized new-denormalized)))))))
(defn remove-query-watch [app registry-key]
(remove-watch (:com.fulcrologic.fulcro.application/state-atom app) registry-key))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment