### Install dependencies and start development server Source: https://github.com/day8/re-frame/blob/master/examples/todomvc/README.md Install project dependencies using npm and start the shadow-cljs hot-reloading development server. ```sh npm install npm run watch ``` -------------------------------- ### re-frame Flows Setup and Example Application Source: https://github.com/day8/re-frame/blob/master/docs/Flows.md Sets up re-frame subscriptions and event handlers for a room calculator example. Includes UI components to display and increment room dimensions, demonstrating the flow in action. ```clojure (ns re-frame.example.flows (:require [re-frame.alpha :as rf] [reagent.dom.client :as rdc])) ``` ```clojure (rf/reg-sub :width (fn [db [_ room]] (get-in db [room :width]))) (rf/reg-sub :length (fn [db [_ room]] (get-in db [room :length]))) (rf/reg-event-db :inc-w (fn [db [_ room]] (update-in db [room :width] inc))) (rf/reg-event-db :inc-h (fn [db [_ room]] (update-in db [room :length] inc))) (rf/reg-event-db :init (fn [db [_ room]] (-> db (update :kitchen merge {:width 10 :length 15}) (update :garage merge {:width 20 :length 20})))) ``` ```clojure (def clickable {:cursor "pointer" :border "2px solid grey" :user-select "none"}) (defn room-form [room] [:form [:h4 room " calculator"] "width:" @(rf/subscribe [:width room]) [:span {:style clickable :on-click #(rf/dispatch [:inc-w room])} "+"] [:br] "length:" @(rf/subscribe [:length room]) [:span {:style clickable :on-click #(rf/dispatch [:inc-h room])} "+"] ]) ``` -------------------------------- ### Reg-sub Example Source: https://github.com/day8/re-frame/blob/master/docs/flow-mechanics.md This is a standard `reg-sub` example demonstrating input signals and computation. ```clojure (reg-sub :visible-todos (fn [query-v _] [(subscribe [:todos]) (subscribe [:showing])]) (fn [[todos showing] _] (let [filter-fn (case showing :active (complement :done) :done :done :all identity)] (filter filter-fn todos)))) ``` -------------------------------- ### Setup app-db with dispatch-sync Source: https://github.com/day8/re-frame/blob/master/docs/Testing.md Use `dispatch-sync` to cumulatively build up the `app-db` state during test setup. This ensures immediate handling of events for predictable state changes. ```clojure ;; setup - cummulatively build up db (dispatch-sync [:initialise-db]) (dispatch-sync [:clear-panel]) (dispatch-sync [:draw-triangle 1 2 3]) ;; execute (dispatch-sync [:select-triange :other :stuff]) ;; validate that the value in 'app-db' is correct ;; perhaps with subscriptions ``` -------------------------------- ### Interactive Keyword Namespace and Keyword Function Examples Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Provides interactive examples for manipulating keywords using built-in functions like 'namespace', 'name', and 'keyword'. These snippets test keyword functionality. ```clojurescript (namespace :a) ``` ```clojurescript (keyword (name :a)) ``` ```clojurescript (keyword (namespace :a/b) (name :a/b)) ``` -------------------------------- ### Basic `reduce` with `+` Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Demonstrates the fundamental usage of `reduce` to sum elements in a collection, starting with an initial value. ```clojure (reduce + 0 [1 2 4]) ``` -------------------------------- ### Interactive Form Evaluation Examples Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Provides interactive examples for evaluating simple ClojureScript forms. These snippets allow for direct experimentation with form evaluation. ```clojurescript (inc (dec 1)) ``` ```clojurescript (odd? (inc (dec 1))) ``` ```clojurescript (= (inc (dec 1)) 1) ``` -------------------------------- ### Example Interceptor Creation Source: https://github.com/day8/re-frame/blob/master/docs/api-re-frame.core-instrumented.md Demonstrates how to define a custom interceptor using the `->interceptor` function, specifying :id, :before, and :after logic. ```clojure (def my-interceptor (->interceptor :id :my-interceptor :before (fn [context] ... modifies and returns `context`) :after (fn [context] ... modifies and returns `context`))) ``` -------------------------------- ### Example Effect Map Source: https://github.com/day8/re-frame/blob/master/docs/api-builtin-effects.md An example of an effect map returned by an event handler, showcasing the :db and :fx effects. ```clojure {:db new-db :fx [ [:dispatch [:some-id]] [:full-screen true] [:http {:method :GET :url "http://somewhere.com/"}]]} ``` -------------------------------- ### Basic List Evaluation Example Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Demonstrates the fundamental evaluation of a list as a function call with arguments. ```clojurescript (f arg1 arg2 arg3) ``` -------------------------------- ### Initialize and Mount Application UI Source: https://github.com/day8/re-frame/blob/master/docs/dominoes-live.md Sets up the application by creating a root for the main UI and defining functions to initialize the app-db and mount the UI. Uses dispatch-sync for initial state setup. ```clojure (defonce dominoes-live-app-root (rdc/create-root (js/document.getElementById "dominoes-live-app"))) (defn mount-ui [] (rdc/render dominoes-live-app-root [ui])) ;; mount the application's ui (defn run [] (rf/dispatch-sync [:initialize]) ;; puts a value into application state (mount-ui)) ``` -------------------------------- ### Run the Dominoes Live Application Source: https://github.com/day8/re-frame/blob/master/docs/dominoes-live.md Calls the run function to initialize the application state and mount the UI. This is the entry point for starting the application. ```clojure (run) ``` -------------------------------- ### Calling `greet` function (friendly) Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Example of calling the `greet` function with a friendly flag set to true. ```clojure (greet "Mum" true) ``` -------------------------------- ### Example -db Handler Source: https://github.com/day8/re-frame/blob/master/docs/Interceptors.md A typical -db event handler takes the current database and the event vector, returning a new database. ```clojure (fn [db event] ;; takes two params (assoc db :flag true)) ;; returns a new db ``` -------------------------------- ### Run MkDocs Material with Docker (Linux) Source: https://github.com/day8/re-frame/blob/master/docs/README.md Start a local development server using Docker for hot-reloading documentation. This command is suitable for Linux environments. ```sh docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material:5.1.1 ``` -------------------------------- ### Dispatching an Event Source: https://github.com/day8/re-frame/blob/master/docs/Interceptors.md Example of dispatching an event that will be handled by an event handler. ```clojure (dispatch [:delete-item 42]) ``` -------------------------------- ### Example of a legacy subscription query Source: https://github.com/day8/re-frame/blob/master/docs/api-re-frame.alpha-instrumented.md Illustrates how a legacy subscription is invoked using a vector, where the first element is the query ID and subsequent elements are arguments. ```clojure (sub [::greet {:name "dave"}]) ``` -------------------------------- ### Run MkDocs Material with Docker (Windows/Mac) Source: https://github.com/day8/re-frame/blob/master/docs/README.md Start a local development server using Docker for hot-reloading documentation. This command is suitable for Windows PowerShell and Mac. ```sh docker run --rm -it -p 8000:8000 -v "%cd%":/docs squidfunk/mkdocs-material:5.1.1 ``` -------------------------------- ### Vector to Query Map Conversion Example Source: https://github.com/day8/re-frame/blob/master/docs/api-re-frame.alpha-instrumented.md Shows how a query vector is converted into a map, preserving the original vector in `:re-frame/query-v` if parameters are not named. ```clojure {:re-frame/q ::items :re-frame/lifecycle :safe :re-frame/query-v [::items 1 2 3]} ``` -------------------------------- ### Calling `greet` function (unfriendly) Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Example of calling the `greet` function with a friendly flag set to false. ```clojure (greet "Noisy Neighbours" false) ``` -------------------------------- ### Registering a Subscription Source: https://github.com/day8/re-frame/blob/master/docs/Flows.md Example of registering a subscription to derive a value based on other subscriptions. This subscription's value changes when its inputs change. ```clojure (rf/reg-sub ::garage-area-sub (fn [_] [(subscribe [:width]) (subscribe [:length])]) (fn [[w h] _] (* w h))) ``` -------------------------------- ### Context Threading Example Source: https://github.com/day8/re-frame/blob/master/docs/Interceptors.md Demonstrates how the context map is threaded through the `:before` functions of an interceptor chain in forward order, and then through the `:after` functions in reverse order. ```clojure ;; start by creating a context map (let [context {:coeffects {} :effects {} ...}]) (-> context ;; Thread `context` through all the `:before` functions. ;; This phase is usually concerned with building up `:coeffects` ((:before std1) ) ;; noop ((:before std2) ) ;; adds `:event` and `:db` to `:coeffects` ((:before in1) ) ((:before in2) ) ((:before ih) ) ;; Domino 2 - handler called & return value put into `:effects` ;; Now backwards through the `:after` functions ;; This phase is usually concerned with building up or processing `:effects` ;; But could involve side effects like logging, or undo/redo state actions, etc ((:after ih) ) ;; noop ((:after in2) ) ((:after in1) ) ((:after std2) ) ;; noop ((:after std1) ) ;; Domino 3 - all the `:effects` are processed ``` -------------------------------- ### Query Map to Vector Conversion Example Source: https://github.com/day8/re-frame/blob/master/docs/api-re-frame.alpha-instrumented.md Illustrates how a query map is converted into a vector, including metadata for the original map and parameters. ```clojure ^{:re-frame/query-m {:re-frame/q ::items}} [::items {:re-frame/q ::items}] ``` -------------------------------- ### x86 Assembly Instructions Example Source: https://github.com/day8/re-frame/blob/master/docs/data-oriented-design.md Presents a snippet of x86 assembly instructions. This serves as an analogy to demonstrate how low-level instructions can be viewed as data executable by a specific machine. ```assembly mov eax, ebx sub eax, 216 mov BYTE PTR [ebx], 2 ``` -------------------------------- ### Run re-frame tests with bb watch Source: https://github.com/day8/re-frame/blob/master/CONTRIBUTING.md Use this command to build the tests and run them in one step. Ensure you have npm, babashka, and chromium installed. ```sh bb watch ``` -------------------------------- ### Rewriting Reg-sub with Reg-sub-raw Source: https://github.com/day8/re-frame/blob/master/docs/flow-mechanics.md This shows how the previous `reg-sub` example can be rewritten using `reg-sub-raw` by wrapping the logic in a `reaction` and using `subscribe` for inputs. ```clojure (reg-sub-raw :visible-todos (fn [app-db query-v] (reaction (let [todos @(subscribe [:todos]) showing @(subscribe [:showing]) filter-fn (case showing :active (complement :done) :done :done :all identity)] (filter filter-fn todos)))) ``` -------------------------------- ### Reagent Ratoms and Reactions Example Source: https://github.com/day8/re-frame/blob/master/docs/flow-mechanics.md Demonstrates how `ratom` and `reaction` work together to create a reactive flow. Changes in a root `ratom` trigger re-computations in dependent `reactions`, updating their values automatically. ```clojure (ns example1 (:require-macros [reagent.ratom :refer [reaction]]) ;; reaction is a macro (:require [reagent.core :as reagent])) (def app-db (reagent/atom {:a 1})) ;; our root ratom (signal) (def ratom2 (reaction {:b (:a @app-db)})) ;; reaction wraps a computation, returns a signal (def ratom3 (reaction (condp = (:b @ratom2) ;; reaction wraps another computation 0 "World" 1 "Hello"))) ;; Notice that both computations above involve de-referencing a ratom: ;; - app-db in one case ;; - ratom2 in the other ;; Notice that both reactions above return a ratom. ;; Those returned ratoms hold the (time varying) value of the computations. (println @ratom2) ;; ==> {:b 1} ;; a computed result, involving @app-db (println @ratom3) ;; ==> "Hello" ;; a computed result, involving @ratom2 (reset! app-db {:a 0}) ;; this change to app-db, triggers re-computation ;; of ratom2 ;; which, in turn, causes a re-computation of ratom3 (println @ratom2) ;; ==> {:b 0} ;; ratom2 is result of {:b (:a @app-db)} (println @ratom3) ;; ==> "World" ;; ratom3 is automatically updated too. ``` -------------------------------- ### Simple Extractor Subscription Source: https://github.com/day8/re-frame/blob/master/docs/correcting-a-wrong.md This is an example of a simple 'Layer 2' subscription that extracts a value directly from app-db. Repetition of such subscriptions is often good and serves a purpose. ```clojure (reg-sub :a (fn [db _] (:a db))) ``` -------------------------------- ### Pure event handler using coeffects for LocalStore Source: https://github.com/day8/re-frame/blob/master/docs/Coeffects.md This refactored example uses `reg-event-fx` and expects the required data (e.g., from LocalStore) to be provided within the `cofx` map. This makes the handler pure. ```clojure (reg-event-fx ;; note: -fx :load-defaults (fn [cofx event] ;; cofx means coeffects (let [val (:local-store cofx) ;; <-- get data from cofx db (:db cofx)] ;; <-- more data from cofx {:db (assoc db :defaults val)}))) ;; returns an effect ``` -------------------------------- ### Collected re-frame Events Example Source: https://github.com/day8/re-frame/blob/master/docs/data-oriented-design.md Illustrates a collection of re-frame events that model user intent and system actions. These events are treated as data instructions for the re-frame virtual machine. ```clojure (def collected-events [ [:clear] [:enter-draw-mode] [:new-shape :triangle 1 2 3] [:select-object 23] [:rename "a better name"] [:delete-selection] .... ]) ``` -------------------------------- ### Example of Registering a Subscription Handler Source: https://github.com/day8/re-frame/blob/master/docs/dominoes-live.md Illustrates the basic structure for registering a subscription handler with re-frame. It associates a query ID with a function that computes the query's result from the application state. ```clojure (rf/reg-sub :some-query-id ;; query id (used later in subscribe) a-query-fn) ;; the function which will compute the query ``` -------------------------------- ### Initialize and Render re-frame App Source: https://github.com/day8/re-frame/blob/master/docs/Flows.md Use `rf/dispatch-sync` to initialize the application. Then, create a root for rendering and render the main app container with its components. ```clojure (rf/dispatch-sync [:init]) (defonce item-counter-requirements-root (rdc/create-root (js/document.getElementById "item-counter-requirements"))) (rdc/render item-counter-requirements-root [app-container [debug-app-db] [controls] [requirement-picker] [warning] [items]]) ``` -------------------------------- ### `let` form with conditional logic Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Demonstrates using `let` to bind variables that are then used in a conditional expression. This example correctly compares strings lexicographically and returns the greater one. ```clojure (let [a "the pen" b "a sword"] (if (> a b) a b)) ``` -------------------------------- ### Open the application in the browser Source: https://github.com/day8/re-frame/blob/master/examples/todomvc/README.md Once the build is complete, open the application in your browser at the specified local address. ```sh open http://localhost:8280 ``` -------------------------------- ### Function with multiple arguments and map return Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md An interactive example of a `fn` that accepts two arguments and returns a map where the first argument is the key and the second is the value. Call it with :a and 4. ```clojurescript (fn [x y] {x y}) ``` -------------------------------- ### Navigate to the TodoMVC directory Source: https://github.com/day8/re-frame/blob/master/examples/todomvc/README.md Change the current directory to the re-frame/examples/todomvc directory. ```sh cd re-frame/examples/todomvc ``` -------------------------------- ### Pure React Component Example Source: https://github.com/day8/re-frame/blob/master/docs/EffectfulHandlers.md An example of a pure re-frame component that returns a description of the desired DOM structure. Reagent/React handles the side-effect of mutating the DOM. ```clojure (defn say-hi [name] [:div "Hello " name]) ``` -------------------------------- ### Correctly Update DB with reg-event-fx Source: https://github.com/day8/re-frame/blob/master/docs/FAQs/use-cofx-as-fx.md When using `reg-event-fx`, return a map of effects. This example shows the correct way to update the `:db` coeffect by returning it as part of the effects map. ```clojure (reg-event-fx ::cow-clicked (fn [{:keys [db] :as cofx} _] {:db (update db :clicks inc)})) ``` -------------------------------- ### Get a snapshot of live query vectors Source: https://github.com/day8/re-frame/blob/master/docs/releases/2026.md Use live-query-vs to get a sequence of all currently live cached query vectors. This is useful for monitoring cache size. ```clojure (count (re-frame.core/live-query-vs)) ``` -------------------------------- ### Test Event Handler with Literal DB and Event Source: https://github.com/day8/re-frame/blob/master/docs/Testing.md A basic test setup using a literal map for `db` and a literal vector for the event. This approach can be fragile if the `db` structure changes. ```clojure ;; a test (let [ ;; setup - create db and event db {:some 42 :thing "hello"} ; a literal event [:select-triangle :other :event :args] ;; execute result-db (select-triange db event)] ;; validate that result-db is correct) (is ...) ) ``` -------------------------------- ### Event Handler with Side Effect: HTTP GET Request Source: https://github.com/day8/re-frame/blob/master/docs/EffectfulHandlers.md This handler performs an HTTP GET request, a significant side effect. This approach complicates reasoning, testing, and event replay. ```clojure (reg-event-db :my-event (fn [db [_ a]] (GET "http://json.my-endpoint.com/blah" ;; dirty great big side-effect {:handler #(dispatch [:process-response %1]) :error-handler #(dispatch [:bad-response %1])}) (assoc db :flag true))) ``` -------------------------------- ### Application Bootstrap Function Source: https://github.com/day8/re-frame/blob/master/docs/Loading-Initial-Data.md Initializes the application by dispatching an event to set initial data and then rendering the main component. This is the entry point for the re-frame app. ```clojure (defn ^:export main ;; call this to bootstrap your app [] (re-frame.core/dispatch [:initialise-db]) (reagent.dom/render [top-panel] (js/document.getElementById "app"))) ``` -------------------------------- ### Usage Example for re-frame.tooling Source: https://github.com/day8/re-frame/blob/master/docs/api-re-frame.tooling.md Demonstrates how to require and use functions from the re-frame.tooling namespace for dispatching events with custom effects and registering trace callbacks. Also shows how to access live subscription cache and handler registry atoms. ```clojure (require '[re-frame.tooling :as rft]) (rft/dispatch-with [:my-event] {:effect-id (fn [_] ...)}) (rft/register-trace-cb :my-tooling (fn [traces] ...)) @rft/query->reaction ;; live subscription cache @rft/kind->id->handler ;; registrar atom ``` -------------------------------- ### Generate API Documentation Source: https://github.com/day8/re-frame/blob/master/docs/README.md Build the API documentation by running the ns-to-markdown command. This is generally done once. ```sh cd docs/ clojure -m ns-to-markdown ../src/re_frame/core.cljc > api-re-frame.core.md ``` -------------------------------- ### Calling `items-text` with no items Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Example of calling the `items-text` function with an empty list. ```clojure (items-text []) ``` -------------------------------- ### Bootstrap with Multiple Service Data Loads Source: https://github.com/day8/re-frame/blob/master/docs/Loading-Initial-Data.md Initializes the app and dispatches events to load data from multiple backend services concurrently. This is useful when the app depends on data from several sources. ```clojure (defn ^:export main ;; call this to bootstrap your app [] (re-frame.core/dispatch [:initialise-db]) ;; basics (re-frame.core/dispatch [:load-from-service-1]) ;; ask for data from service-1 (re-frame.core/dispatch [:load-from-service-2]) ;; ask for data from service-2 (reagent.dom/render [top-panel] (js/document.getElementById "app"))) ``` -------------------------------- ### Clone the re-frame repository Source: https://github.com/day8/re-frame/blob/master/examples/todomvc/README.md Clone the re-frame repository from GitHub to access the examples. ```sh git clone https://github.com/day8/re-frame.git ``` -------------------------------- ### Function with no arguments Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md An interactive example of a `fn` that takes no arguments. It is called without any arguments. ```clojurescript (fn []) ``` -------------------------------- ### Initializing Application and Rendering Error UI Source: https://github.com/day8/re-frame/blob/master/docs/Flows.md Dispatches an initial event to the application and renders the UI including controls, the warning component, and the items list. Sets up the UI to display error states. ```clojure (rf/dispatch-sync [:init]) (defonce item-counter-error-root (rdc/create-root (js/document.getElementById "item-counter-error"))) (rdc/render item-counter-error-root [app-container [debug-app-db] [controls] [warning] [items]]) ``` -------------------------------- ### Get re-frame Version Source: https://github.com/day8/re-frame/blob/master/docs/api-re-frame.core-instrumented.md Retrieve the runtime-readable string identifying the deployed re-frame artifact. ```clojure re-frame.config/version ``` -------------------------------- ### Creating and Rendering React Root Source: https://github.com/day8/re-frame/blob/master/docs/Flows.md Initializes a React root and renders the application container with controls and items. This sets up the basic UI for item management. ```clojure (defonce item-counter-basic-root (rdc/create-root (js/document.getElementById "item-counter-basic"))) (rdc/render item-counter-basic-root [app-container [controls] [items]]) ``` -------------------------------- ### Dispatch with effect-id using re-frame.tooling Source: https://github.com/day8/re-frame/blob/master/docs/releases/2026.md Example of using dispatch-with from re-frame.tooling to dispatch an event with an effect-id. ```clojure (rft/dispatch-with [:my-event] {:effect-id (fn [_] ...)}) ``` -------------------------------- ### Calling `items-text` with a single item Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Example of calling the `items-text` function with a list containing a single item. ```clojure (items-text [:towel]) ``` -------------------------------- ### Wiring re-frame Component with I/O Functions Source: https://github.com/day8/re-frame/blob/master/docs/reusable-components.md This example shows how to create I/O functions that wrap `subscribe` and `dispatch`, and then pass them into a sub-component. This allows the parent context to manage the component's interaction with the application's state. ```clojure (defn customer-list [] (let [get-customer (fn [id] @(subscribe [:customer id])) put-customer (fn [id field val] (dispatch [:cust-change id field val]))]) [:div (for [id @(subscribe [:all-customer-ids])] ^{:key id} [customer-names id get-customer put-customer])]) ``` -------------------------------- ### Calling `items-text` with multiple items Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Example of calling the `items-text` function with a list containing multiple items. ```clojure (items-text [:towel :sunglasses]) ``` -------------------------------- ### Registering a Coeffect Handler for :local-store Source: https://github.com/day8/re-frame/blob/master/docs/Coeffects.md This example shows how to register a handler for the `:local-store` coeffect. It retrieves a value from the browser's local storage using the provided key and associates it with the `:local-store` key in the coeffects map. ```clojure (reg-cofx ;; new registration function :local-store (fn [coeffects local-store-key] (assoc coeffects :local-store (js->clj (.getItem js/localStorage local-store-key))))) ``` -------------------------------- ### Register trace callback using re-frame.tooling Source: https://github.com/day8/re-frame/blob/master/docs/releases/2026.md Example of registering a trace callback for a specific tool using re-frame.tooling. ```clojure (rft/register-trace-cb :my-tool (fn [traces] ...)) ``` -------------------------------- ### Compile an optimized version of the application Source: https://github.com/day8/re-frame/blob/master/examples/todomvc/README.md Compile the application for production using npm and the release command. ```sh npm install npm run release ``` -------------------------------- ### Basic `fn` form and function call Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Demonstrates the simplest `fn` form which takes one argument and returns it. Shows how to call this function with a string argument. ```clojurescript ; Aside: a line which starts with a semi-colon is a comment ; The following is a two element list: ; - the 1st is (fn [x] x) and that's a function (created by an `fn` form) ; - the 2nd element is a string "the actual arg" ((fn [x] x) "the actual arg") ``` -------------------------------- ### Dynamic Binding Helper Source: https://github.com/day8/re-frame/blob/master/docs/EPs/002-ReframeInstances.md A macro for temporarily binding a frame context, useful for tests, REPLs, or setup code. ```APIDOC ## Dynamic Binding Helper ### Description A macro for temporarily binding a frame context, useful for tests, REPLs, or setup code. ### API - `(rf/with-frame frame & body)` - Executes the body within the context of the specified frame. ``` -------------------------------- ### Apply `map` with `count` Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Use `map` with the `count` function to get the number of elements in each string within a collection. ```clojure (map count ["hi" "world"]) ``` -------------------------------- ### Open the optimized application Source: https://github.com/day8/re-frame/blob/master/examples/todomvc/README.md Access the compiled, optimized version of the application by opening the index.html file in your browser. ```sh resources/public/index.html ``` -------------------------------- ### ClojureScript Symbols Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Shows examples of ClojureScript symbols, which are names bound to values. These can refer to built-in functions or user-defined variables. ```clojurescript inc ``` ```clojurescript + ``` ```clojurescript yours ``` -------------------------------- ### Defining a No-Data Effect Handler Source: https://github.com/day8/re-frame/blob/master/docs/Effects.md Example of an effect handler that does not utilize the provided value, suitable for effects that only trigger an action. ```clojure (reg-fx :exit-fullscreen (fn [_] ;; we don't bother with that nil value (.exitFullscreen js/document))) ``` -------------------------------- ### Initializing `app-db` with an Event Handler Source: https://github.com/day8/re-frame/blob/master/docs/Loading-Initial-Data.md Define an event handler using `reg-event-db` to set the initial state of `app-db`. This handler returns a map that becomes the new value of `app-db`. ```clojure (re-frame.core/reg-event-db :initialise-db ;; usage: (dispatch [:initialise-db]) (fn [_ _] ;; Ignore both params (db and event) {:display-name "DDATWD" ;; return a new value for app-db :items [1 2 3 4]})) ``` -------------------------------- ### reg-sub-raw Example Rewriting reg-sub Source: https://github.com/day8/re-frame/blob/master/docs/flow-mechanics.md Demonstrates how a typical `reg-sub` definition can be rewritten using `reg-sub-raw` to achieve the same result but with a `reaction` as the output. ```APIDOC ## Rewriting reg-sub with reg-sub-raw ### Original `reg-sub` Example ```clj (reg-sub :visible-todos (fn [query-v _] [(subscribe [:todos]) (subscribe [:showing])]) (fn [[todos showing] _] (let [filter-fn (case showing :active (complement :done) :done :done :all identity)] (filter filter-fn todos)))) ``` ### Rewritten using `reg-sub-raw` ```clj (reg-sub-raw :visible-todos (fn [app-db query-v] ; app-db not used, name shown for clarity (reaction (let [todos @(subscribe [:todos]) ; input signal #1 showing @(subscribe [:showing]) ; input signal #2 filter-fn (case showing :active (complement :done) :done :done :all identity)] (filter filter-fn todos))))) ``` ### Explanation Both versions deliver the same result when accessed via `(subscribe [:visible-todos])`. The `reg-sub-raw` version explicitly wraps the computation in a `reaction`, defining its inputs using `subscribe` within the reaction body. ``` -------------------------------- ### Dispatch Delete Item Event Source: https://github.com/day8/re-frame/blob/master/docs/dominoes-30k.md An example of dispatching a re-frame event to delete an item, specifying the event type and the item ID. ```clojure #(re-frame.core/dispatch [:delete-item item-id]) ``` ```clojure [:delete-item 2486] ``` -------------------------------- ### Impure Event Handler with Side-Effect Source: https://github.com/day8/re-frame/blob/master/docs/EffectfulHandlers.md An example of an impure re-frame event handler that directly performs a side-effect (dispatching another event). ```clojure (reg-event-db :my-event (fn [db [_ a]] (dispatch [:do-something-else 3]))) ``` -------------------------------- ### Inspect entire app-db in UI (pprint) Source: https://github.com/day8/re-frame/blob/master/docs/FAQs/Inspecting-app-db.md Embed pretty-printed output of the entire re-frame app-db directly into your UI for inspection. Requires `cljs.pprint` to be required. ```clojure [:pre (with-out-str (pprint @re-frame.db/app-db))] ``` -------------------------------- ### Using Custom reg-event-db Source: https://github.com/day8/re-frame/blob/master/docs/FAQs/GlobalInterceptors.md Example of how to use the custom `my-reg-event-db` function to register an event handler with an automatically injected global interceptor. ```clojure (my-reg-event-db :event-id (fn [db v] ...)) ``` -------------------------------- ### Call a Trivial Reagent Component Source: https://github.com/day8/re-frame/blob/master/docs/flow-mechanics.md Demonstrates how to call a simple Reagent component and its output. ```clojure (greet) ;; ==> [:div "Hello ratoms and reactions"] ``` -------------------------------- ### Use the Sliding Lifecycle Source: https://github.com/day8/re-frame/blob/master/docs/api-re-frame.alpha-instrumented.md Demonstrates how to subscribe to a query using the custom ':sliding' lifecycle. Subsequent subscriptions beyond the cache limit will trigger the sliding behavior. ```clojure (re-frame.alpha/sub ^{:re-frame/lifecycle :sliding} [:hi 1]}) ``` ```clojure (re-frame.alpha/sub ^{:re-frame/lifecycle :sliding} [:hi 2]}) ``` ```clojure (re-frame.alpha/sub ^{:re-frame/lifecycle :sliding} [:hi 3]}) ``` ```clojure (re-frame.alpha/sub ^{:re-frame/lifecycle :sliding} [:hi 4]}) ;; now [:hi 1] is cleared ``` -------------------------------- ### Hashmap with Namespaced Keywords Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md An example of a ClojureScript hashmap utilizing namespaced keywords as keys. This pattern is frequently used for structured data representation. ```clojurescript { :user/id 1 :user/name "Barry" :user/age 28 :user/company "SpaceX" :role/name "Rocket Sharpener" } ``` -------------------------------- ### Hashmap as a function (key lookup) Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Demonstrates how a hashmap can act as a function. When a hashmap is the first element in a form, the second element is treated as a key to look up within the hashmap. ```clojure ({:a 11} :a) ``` -------------------------------- ### Nested Extractor Subscription Source: https://github.com/day8/re-frame/blob/master/docs/correcting-a-wrong.md Another example of a simple subscription that extracts a value from a nested path within app-db. This pattern is common and should not be over-abstracted. ```clojure (reg-sub :b (fn [db _] (-> db :top :b))) ``` -------------------------------- ### Simple -db Handler vs. Flexible -fx Handler Source: https://github.com/day8/re-frame/blob/master/docs/EffectfulHandlers.md Illustrates two handlers that achieve the same result: one using the simpler -db handler and another using the more flexible -fx handler for updating a flag. ```clojure (reg-event-db :set-flag (fn [db [_ new-value]] (assoc db :flag new-value))) ``` ```clojure (reg-event-fx :set-flag (fn [cofx [_ new-value]] {:db (assoc (:db cofx) :flag new-value)})) ``` -------------------------------- ### Hiccup with Conditional Computation Example Source: https://github.com/day8/re-frame/blob/master/docs/data-oriented-design.md Demonstrates a hiccup data structure that includes a conditional expression. This highlights how data can incorporate computation before being interpreted. ```clojure [:div (if friendly? "Hello" "Go away") " world"] ``` -------------------------------- ### Define a Trivial Reagent Component Source: https://github.com/day8/re-frame/blob/master/docs/flow-mechanics.md Components are pure functions that take data and return Hiccup. This example shows a simple component with no parameters. ```clojure (defn greet [] [:div "Hello ratoms and reactions"]) ``` -------------------------------- ### Exercise: `map` with keywords and collections Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md An exercise demonstrating `map` with keywords and a collection of maps, potentially involving keys not present in all maps. ```clojure (map {:a 1 :b 2 :c 3} [:a :b :c :d]) ``` -------------------------------- ### Apply `reduce` with `max` function Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Use `reduce` with a custom `max` function to find the largest element in a collection, starting from an initial value. ```clojure (reduce max 0 [1 2 4]) ``` -------------------------------- ### Conceptual evaluation of `reduce` Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Illustrates the step-by-step evaluation process of `reduce` when summing a collection. ```clojure (+ (+ (+ 0 1) 2) 4) ``` -------------------------------- ### Comparing Data Structures After Assoc Source: https://github.com/day8/re-frame/blob/master/docs/clojurescript.md Shows how `assoc` creates new data structures. This example compares the original with a modified version and checks for identity. ```clojure (let [car1 {:doors 2} car2 (assoc car1 :doors 4) car3 (assoc car2 :doors 2)] [(= car1 car3) (identical? car1 car3)]) ``` -------------------------------- ### Register Re-frame Subscriptions for Kitchen Metrics Source: https://github.com/day8/re-frame/blob/master/docs/flows-advanced-topics.md These re-frame subscriptions are used to retrieve kitchen area, height, and calculate the kitchen volume. The volume calculation depends on both area and height. ```clojure (rf/reg-sub ::kitchen-area (fn [db _] (get-in db [:kitchen :area]))) (rf/reg-sub ::kitchen-height (fn [db _] (get-in db [:kitchen :height]))) (rf/reg-sub ::kitchen-volume (fn [_] [(rf/subscribe [::kitchen-area]) (rf/subscribe [::kitchen-height])]) (fn [[area height] _] (* area height))) ```