Questions
My webpage only has the output: {:user {}} with the following code.
(ns omn1.core
(:require
[om.next :as om :refer-macros [defui]]
[om.dom :as dom :refer [div]]
[goog.dom :as gdom]))
(defui MyComponent
static om/IQuery
(query [this] [:user])
Object
(render
[this]
(let [data (om/props this)]
(div nil (str data)))))
(def app-state (atom {:user {:name "Fenton"}}))
(defn reader [{q :query st :state} _ _]
(.log js/console (str "q: " q))
{:value (om/db->tree q #app-state #app-state)})
(def parser (om/parser {:read reader}))
(def reconciler
(om/reconciler
{:state app-state
:parser parser}))
(om/add-root! reconciler MyComponent (gdom/getElement "app"))
When I check the browser console, I notice that my query is nil. Why
doesn't it get passed into my reader function?
This comes from a motivation to keep my code to a minimal # of LOC as possible, and also DRY. So I'd like to have one read function that will work with a properly set up database, and normal nominal queries. If you pass regular queries to om/db->tree indeed db->tree does this. db->tree will take any proper query and return you a filled out tree of data. Maybe another way to phrase the question is can someone demonstrate a reader function that does this? I.e. leveraging db->tree to resolve the value of a query. I don't want to write a custom reader for each query I have. If all my queries obey the regular query syntax AND my DB is properly formatted, I should be able to use one reader function, no?
The example provided in the om.next quick start - thinking with links doesn't work:
(defmethod read :items
[{:keys [query state]} k _]
(let [st #state]
{:value (om/db->tree query (get st k) st)}))
as stated before query is nil sometimes, and the 2nd and 3rd arguments are different from what is proposed as how to use this function from the tests which all use: st for both 2nd and 3rd arguments. Confused.
From the Om.Next Quick Start tutorial (https://github.com/omcljs/om/wiki/Quick-Start-(om.next)), read has this signature:
[{:keys [state] :as env} key params]
So there is no access to a query data structure.
Usually the setup is to have a multimethod for each query, and use the query's params to return some part of the state:
(defmulti read (fn [env key params] key))
(defmethod read :animals/list
[{:keys [state] :as env} key {:keys [start end]}]
{:value (subvec (:animals/list #state) start end)})
Here :animals/list is the key of the query. So this is how you can access the key and params of the query.
Related
I am making an HTTP request:
(defn main-panel []
(def API-URL "https://api.chucknorris.io/jokes/random")
(defn getFileTree []
(go (let [response (<! (http/get API-URL
{:with-credentials? false
:headers {"Content-Type" "application/json"}}))]
(:status response)
(js/console.log (:body response))))) ; prints a very complex data structure
(go
(let [result (<! (getFileTree))]
(.log js/console (:body result)))) ; prints null
:reagent-render
(fn []
[:h1 "kjdfkjndfkjn"]))
But I can't get to the "joke" in the returned object, array item 13:
How do I assign this value to a let or def?
Also, why does the second console.log print null?
Update
I am now moving on from using reagent atoms to reframe.
This is my component that successfully GETs data, updates the re-frame 'database':
(defn main-panel []
(def API-URL "https://api.chucknorris.io/jokes/random")
(def request-opts {:with-credentials? false})
(defn getFileTree []
(go (let [response (<! (http/get API-URL request-opts))]
(re-frame/dispatch [:update-quote response]))))
(defn render-quote []
(println (re-frame/subscribe [::subs/quote])) ;successfully prints API data as in screenshot below
(fn []
(let [quote-data (re-frame/subscribe [::subs/quote])
quote-text (if quote-data (:value quote-data) "...loading...")]
[:div
[:h3 "Chuck quote of the day"]
[:em quote-text]])))
(fn []
(getFileTree)
[render-quote]))
But this is the object I get back from the re-frame database:
As you can see it comes wrapped in the Reaction tags and I can't access the body or value any more. How do I access those?
I have a small working version using the reagent template. Create a new project (assuming you have Leiningen installed) with: lein new reagent chuck. This will create a project with many dependencies, but it works out of the box.
Next, edit the file at src/cljs/chuck/core.cljs and edit it so it looks like the following:
(ns chuck.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [reagent.core :as reagent :refer [atom]]
[cljs-http.client :as http]
[cljs.core.async :refer [<!]]))
(def api-url "https://api.chucknorris.io/jokes/random")
(def request-opts {:with-credentials? false
:headers {"Content-Type" "application/json"}})
(def api-response (atom nil))
(defn get-quote []
(go
(let [response (<! (http/get api-url request-opts))]
(println response)
(reset! api-response response))))
(defn render-quote []
(fn []
(let [quote-data (:body #api-response)
quote-text (if quote-data (:value quote-data) "...loading...")]
[:div
[:h3 "Chuck quote of the day"]
[:em quote-text]])))
(defn quote-page []
(fn []
(do
(get-quote)
[:div
[:header
[render-quote]]
[:footer
[:p "footer here"]]])))
;; -------------------------
;; Initialize app
(defn mount-root []
(reagent/render [quote-page] (.getElementById js/document "app")))
(defn init! []
(mount-root))
I'll explain the relevant bits:
init will bootstrap the basics of the front-end, but in our case it's just calls mount-root which starts reagent telling it to call quote-page and placing the results in the DOM replacing the element with the ID of app.
quote-page calls get-quote which will call the API using the cljs-http library. I'm not checking for errors here, but basically when the request completes (either success or error) it will read the results from the channel (using <!) and place the response in response. The key is that response is a nested ClojureScript map that you can inspect to check if the result was successful or not. Note that I'm also printing the results with println instead of JS interop (.log js/console xxx) because console.log will show the inner details of how the nested map is implemented, which is not relevant for this case.
One the response is available, I store the results of the response in an atom called api-response. The key here is that the atom will contain nothing for a bit (while the request completes) and then the response will be inside it and reagent will take care of detecting the change and re-rendering.
Finally, quote-page calls render-quote which generates the markup for rendering the quote or a placeholder while it loads.
To run the whole thing, open a terminal and run lein run which will start a web server listening on port 3000 by default. In another terminal, run lein figwheel which will compile the ClojureScript code for you. One figwheel is ready it will start a REPL, and you can open the address http://0.0.0.0:3000/ in your computer to view the page.
I will preface this question by saying I am still very much a novice when it comes to Clojure/Script, so besides the very pointed question I will pose any general feedback about style, usage would be greatly appreciated.
I have been building a very simple application with om.next. For client side routing I have decided to use Secretary. My application displays a list of items, and the intention is that when you click on one of those items you can view the details. The implementation at present is via a simple href on an anchor tag (e.g., an href might look like /items/1, where 1 is the id). This is partially because you should be able to navigate to the details URL directly to see the same view. As simple as this sounds, I cannot for the life of me get this to work as desired.
First, let's look at the salient configuration to the reconciler (for brevity I have removed the implementation details of component render throughout)...
(def init-data {:items [{:id 1
:title "stack overflow"
:description "hello, world."
:photos []}
{:id 2
:title "foo"
:description "bar"
:photos []}]})
(defui ListItem
static om/Ident
(ident [this {:keys [id]}]
[:items/by-id id])
static om/IQuery
(query [this]
[:id :title :description :photos]))
(defui Items
static om/IQuery
(query [this]
[{:items (om/get-query ListItem)}]))
(defmulti read om/dispatch)
(defmethod read :items
[{:keys [state query] :as env} key _]
(let [st #state]
{:value (om/db->tree query (get st key) st)}))
(def app-state (atom (om/tree->db Items init-data true)))
(def reconciler
(om/reconciler {:parser (om/parser {:read read})
:state app-state}))
The astute will see that I am trying to think with links, and this much seems to be working as I would expect. It is when I add this component, and try to use it behind a Secretary route, that everything breaks down...
; I tried other approaches, they failed too
(defui Item
static om/IQueryParams
(params [this]
{:id :not-found})
static om/IQuery
(query [this]
'[[:items/by-id ?id]]))
(defn render-component [component]
(let [app (gdom/getElement "app")]
(doto reconciler
(om/remove-root! app)
(om/add-root! component app)))))
(defroute item-path "/items/:id" [id]
(let [component Item]
; this is already less than ideal, as we know the id
; before the first render of the component
(render-component component)
(om/set-query! (om/class->any reconciler component)
{:id (js/parseInt id)})))
The instance of my Item component does not receive the proper state in props as specified in the query (it receives the entirety of app-state). What is most perplexing to me is that if I execute the same query against app-state manually in the REPL I get the right set of data back...
(get-in #app-state [:items/by-id 1])
; {:id 1, :title "stack overflow", :description "hello, world.", :photos []}
The only thing that has worked for me so far is to bypass the reconciler (creating the component instance myself), passing the query value from app-state as props. But that means I can't mutate state via the reconciler, which is a new horrific wrinkle to an otherwise messy, and unkempt conundrum.
What am I missing here? While I have many ideas, the thing I'm most suspicious about is the initialization of app-state via om/tree->db.
I'm trying to understand how to read state from a text box in om.next. As I understand it, we are no longer bound/supposed to use core.async.
As a small example, consider writing in a textbox and binding it to a paragraph element, so that the text you enter automatically appears on the screen.
(def app-state (atom {:input-text "starting text"}))
(defn read-fn
[{:keys [state] :as env} key params]
(let [st #state]
(if-let [[_ v] (find st key)]
{:value v}
{:value :not-found})))
(defn mutate-fn
[{:keys [state] :as env} key {:keys [mytext]}]
(if (= 'update-text key)
{:value {:keys [:input-text]}
:action
(fn []
(swap! state assoc :input-text mytext))}
{:value :not-found}))
(defui RootView
static om/IQuery
(query [_]
[:input-text])
Object
(render [_]
(let [{:keys [input-text]} (om/props _)]
(dom/div nil
(dom/input
#js {:id "mybox"
:type "text"
:value input-text
:onChange #(om/transact! _ '[(update-text {:mytext (.-value (gdom/getElement "mybox"))})])
})
(dom/p nil input-text)))))
This doesn't work.
When firing the onChange event in the input form, the quoted expression does not grab the text from the box.
The first mutation fires and updates, but then subsequent mutations are not fired. Even though the state doesn't changed, should the query read the string from app-state and force the text to be the same?
I would make the :onChange event look like this:
:onChange (fn (_)
(let [v (.-value (gdom/getElement "mybox"))]
#(om/transact! this `[(update-text {:mytext ~v})])))
Here the value v will actually be going through. But also om/transact! needs either a component or the reconciler to be passed as its first parameter. Here I'm passing in this which will be the root component.
This does not seem to be happening as the Quick Start tutorial says:
In Om Next application state changes are managed by a reconciler. The
reconciler accepts novelty, merges it into the application state,
finds all affected components based on their declared queries, and
schedules a re-render.
When I change the select box the mutate function updates the state, but the App component's render function never executes. I can see with #app-state in the REPL that the state has changed and I never see the output in the console from the prn in the App's render function. This is all I see in the console:
[1955.847s] [om.next] transacted '[(om-tutorial.core/switch-topic {:name "b"})], #uuid "c3ba6741-81ea-4cbb-8db1-e86eec26b540"
"read :default" :topics
If I update the state from the REPL with (swap! app-state update-in [:current-topic] (fn [] "b")) then the App's render function does execute. Here is the console output:
"read :default" :topics
"read :default" :current-topic
"App om-props " {:topics [{:name "a"} {:name "b"}], :current-topic "b"}
"Topics om-props " {:topics [{:name "a"} {:name "b"}]}
Here is the full code:
(ns om-tutorial.core
(:require [goog.dom :as gdom]
[om.next :as om :refer-macros [defui]]
[om.dom :as dom]))
(enable-console-print!)
(def app-state (atom {:current-topic "a" :topics [{:name "a"} {:name "b"}]}))
(defmulti read (fn [env key params] key))
(defmethod read :default
[{:keys [state] :as env} key params]
(prn "read :default" key)
(let [st #state]
(if-let [value (st key)]
{:value value}
{:value :not-found})))
(defmulti mutate om/dispatch)
(defmethod mutate 'om-tutorial.core/switch-topic
[{:keys [state]} _ {:keys [name]}]
{:action
(fn []
(swap! state update-in
[:current-topic]
#(identity name)))})
(defui Topics
static om/IQuery
(query [this]
[:topics])
Object
(render [this]
(let [{:keys [topics] :as props} (om/props this)]
(prn "Topics om-props " props)
(apply dom/select #js {:id "topics"
:onChange
(fn [e]
(om/transact! this
`[(switch-topic ~{:name (.. e -target -value)})]))}
(map #(dom/option nil (:name %)) topics)))))
(def topics-view (om/factory Topics))
(defui App
static om/IQuery
(query [this]
'[:topics :current-topic])
Object
(render [this]
(let [{:keys [topics current-topic] :as om-props} (om/props this)]
(prn "App om-props " om-props)
(dom/div nil
(topics-view {:topics topics})
(dom/h3 nil current-topic)))))
(def reconciler
(om/reconciler
{:state app-state
:parser (om/parser {:read read :mutate mutate})}))
(om/add-root! reconciler App (gdom/getElement "app"))
Here is the project.clj file:
(defproject om-tutorial "0.1.0-SNAPSHOT"
:description "My first Om program!"
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.170"]
[org.omcljs/om "1.0.0-alpha24"]
[figwheel-sidecar "0.5.0-SNAPSHOT" :scope "test"]])
I had the same issue in my application and found a workaround (although this might not be the best solution). You can construct your components by passing the om properties of the parent component.
Your ui App could would then look like this:
(defui App
Object
(render [this]
(dom/div nil (topics-view (om/props this)))))
IQuery is definitely the better solution, but I still have the same issue like you. This workaround works in my projects for now and I will definitely take a look at IQuery again.
Edit
The tutorial about Components, Identity and Normalization explains what you have to do to update the UI when it is necessary. This results in a more idiomatic solution.
Om Next is reluctant about triggering re-reads on queries for performance reasons, in order to avoid calling the read functions for them unnecessarily and avoid useless re-renders. To specify that components that query :current-topic should re-render (and the relevant read function called), you can provide these keys in the end of the transact vector:
(om/transact! this
`[(switch-topic ~{:name (.. e -target -value)})
:current-topic])
Reference: https://github.com/omcljs/om/wiki/Documentation-(om.next)#transact
Trying react for the first time, and I want to make a simple todo list app. But every time I press enter to trigger onSubmit it says Uncaught Error: Cannot manipulate cursor outside of render phase, only om.core/transact!, om.core/update!, and cljs.core/deref operations allowed. While I think this is a very good error message, I don't know what to do.
(ns app.core
(:require [om.core :as om :include-macros true]
[sablono.core :as html :refer-macros [html]]))
(def app-state (atom
{:todos [{:todo "first"}
{:todo "second"}]
:current ""}))
(defn to-do
[data]
(om/component
(html [:li (:todo data)])))
(defn to-dos
[data]
(om/component
(html [:div
[:form {:on-submit (fn [e]
(.preventDefault e)
(om/transact! data :todos (fn [v]
(js/console.log (:current data))
(conj v (:current data)))))}
[:input {:type "text"
:placeholder "Enter some text."
:on-change (fn [e] (om/update! data :current (.. e -target -value)))}]]
[:ul
(om/build-all to-do (:todos data))]])))
(om/root to-dos app-state {:target js/document.body})
I think the problem is where you access data inside om/transact! where you should operate on v:
(:current v) instead of (:current data)
or you may try (:current #data) for most recent value of data
There are actually two issues with:
(om/transact! data :todos (fn [v]
(js/console.log (:current data))
(conj v (:current data)))))
One is what #edbond said above: you should use (:current v) rather than (:current data). The other problem, however, is that you are specifying the :todos keyword, and instead, you should simply change data itself, since :current is outside of :todos in your app-state shown. So the correct formulation would be:
(om/transact! data (fn [v]
(js/console.log (:current v))
(conj v (:current v)))))