Liking cljdoc? Tell your friends :D

re-frame-routing

ClojureScript (re-frame) library that manages routing and route state.

re-frame-routing is built on top of bidi and persists route state to re-frame's app state. Registering re-frame-routing to an existing re-frame application is ease.

Step 1: Install

Clojars Project

CircleCI

Step 2: Import Events

(ns app.events.core
  (:require [re-frame-routing.core :as rfr]

            [app.router.core :as router]))

(rfr/register-events {:routes router/routes})

Step 3: Import Subscriptions

(ns app.subscriptions.core
  (:require [re-frame-routing.core :as rfr]))

(rfr/register-subscriptions)

Route Middleware

(Note this API is subject to change in future releases)

Sometimes it's nice to perform work when a route is loading, maybe even prevent the route's view from displaying until that work is done, or even redirect if a user does not have access to view the route. These are good use cases for route-middleware.

To add route-middleware to a route, first create the route-middleware function

(def route-middleware
  (rfr/create-route-middleware {:loading-view loading/render}))

loading-view is a reagent component that will display while your route is loading.

Now let's say you have a sign-in page, but only unauthenticated users should be able to view it. Here is you sign-in route with no middleware

(defmethod containers :sign-in []
  [sign-in/render])

And now we add some middleware

(defmethod containers :sign-in []
  [(route-middleware
    sign-in/render
    [redirect-authenticated])])

Without diving into redirect-authenticated quite yet, let's first look at our route-middleware function. It takes in a view component and a vector of middleware functions (executed from left to right). The result after all functions have executed is the view. The view will receive path and query params as arguments.

Next let's look at redirect-authenticated

(defn redirect-authenticated
  "Redirects authenticated users to the authenticated home page"
  [{:keys [route-query route-params] :as ctx}]
  (let [is-authenticated (re-frame/subscribe [:user/is-authenticated?])]

    (when (true? @is-authenticated)
      (re-frame/dispatch [:router/nav-to "/authenticated-home"]))

    (if (true? @is-authenticated)
      (assoc ctx :is-loading true)
      ctx)))

Middleware functions will be passed a context object and are expected to return a context object. To prevent the execution of the next middleware function in the chain, toggle the is-loading property on the middleware context object to true.

License

Copyright © 2018 Matt O'Connell

Distributed under the Eclipse Public License.

Can you improve this documentation?Edit on GitHub

cljdoc is a website building & hosting documentation for Clojure/Script libraries

× close