Search code examples
clojurescriptreagentsecretary

How to get query parameters in clojurescript?


I'm using secretary and reagent. This is my code :

(def view (atom nil))

(defn layout [view]
  [:div @view])

(reagent/render-component [layout view] (.getElementById js/document "message"))

(secretary/set-config! :prefix "")

(secretary/defroute home-path "/" [query-params]
  (timbre/info "Path : /, query params : " query-params)
  (let [warning (:warning query-params)
        success (:success query-params)
        login-failed (:login_failed query-params)]
    (when warning
      (timbre/info "Warning found : " warning)
      (reset! view [:h4 [:span.label.label-warning warning]]))
    (when success
      (timbre/info "Success found : " success)
      (reset! view [:h4 [:span.label.label-info success]]))
    (when login-failed
      (timbre/info "Login failed")
      (reset! view [:h4 [:span.label.label-warning "Login Failed."]]))))

(let [h (History.)]
 (goog.events/listen h EventType.NAVIGATE #(secretary/dispatch! (.-token %)))
 (doto h
  (.setEnabled true)))

Disregarding the :prefix value (I tried "", "#" and also not setting the :prefix at all) this code only works with routes like :

http://localhost:8080/login#/?success=SuccessMessage

But it doesn't work with routes like :

http://localhost:8080/login?success=SuccessMessage

What I'm actually trying to achieve is to parse the login failure from friend, which in case of failure redirects me to

http://localhost:8080/login?&login_failed=Y&username=someUser

and display login failed message to the user. I don't need to use secretary for this, anything that works to parse the query-parameters would be ok for me.

The hard way would be to parse the query string which I can get with:

(-> js/window .-location .-search)

I believe that this is already done well in some library.


Solution

  • I found it. Using https://github.com/cemerick/url (works for both clojure and clojurescript), one can do :

    (require '[cemerick.url :as url])
    (:query (url/url (-> js/window .-location .-href)))