Skip to content

Instantly share code, notes, and snippets.

@j1mr10rd4n
Created August 6, 2018 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j1mr10rd4n/2daa9d6a2cf75eb0d4557046dbab973a to your computer and use it in GitHub Desktop.
Save j1mr10rd4n/2daa9d6a2cf75eb0d4557046dbab973a to your computer and use it in GitHub Desktop.
Using a fulcro root element from a devcard as a child in a union query (e.g. page router)
(ns myapp-from-template.widgets
(:require [fulcro.client.cards :refer [defcard-fulcro]]
[fulcro.client.primitives :as prim :refer [defsc defui]]
[fulcro.client.dom :as dom]
[fulcro.client.mutations :as m :refer [defmutation]]))
(enable-console-print!)
(def widgets [{:name :red :color "red" :label "danger"}
{:name :green :color "green" :label "safe"}
{:name :orange :color "orange" :label "caution"}])
(defmutation select-widget
[{:keys [name]}]
(action
[{:keys [state]}]
(swap! state assoc-in [:selected-widget] name)))
(defsc WidgetButton
[this
{:keys [name color label]}
{:keys [selected-widget select-widget]}]
{:initial-state (fn [{:keys [name color label]}] {:name name :color color :label label})
:query [:name :color :label]
:ident [:widget-button/by-name :name]}
(dom/div {}
(let [style (if (and selected-widget (= selected-widget name)) {:style {:backgroundColor color}})]
(dom/button (merge {:onClick #(select-widget name)} style) label))))
(def ui-widget-button (prim/factory WidgetButton {:keyfn :name}) )
(defsc WidgetRoot [this {:keys [widget-buttons selected-widget]}]
{:initial-state (fn [_] {:id :my-example :selected-widget nil :widget-buttons (into [] (map #(prim/get-initial-state WidgetButton %) widgets))})
; :ident (fn [] [:my-example :page])
:query [:id :selected-widget {:widget-buttons (prim/get-query WidgetButton)}]}
(let [select-widget (fn [name] (prim/transact! this `[(select-widget {:name ~name})]))]
(dom/div
(map #(ui-widget-button (prim/computed % {:select-widget select-widget
:selected-widget selected-widget})) widget-buttons))))
(defcard-fulcro Widgets
WidgetRoot
{}
{:inspect-data true})
@j1mr10rd4n
Copy link
Author

j1mr10rd4n commented Aug 6, 2018

The component above works as-is in devcards. Note the root component ident is commented out - that will be needed for use in a union query but including in a devcard breaks the card.

The trick is to remember the path to the mutation target is not at the top-level when the component is included in a union query. The assoc-in must use the whole path, e.g. [:my-example :page :selected-widget] in the case shown.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment