How to get query parameters in clojurescript?
Asked Answered
S

2

10

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.

Stenophyllous answered 14/9, 2015 at 20:12 Comment(0)
S
16

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)))
Stenophyllous answered 15/9, 2015 at 6:21 Comment(0)
H
1

From the docs:

If a URI contains a query string it will automatically be extracted to :query-params for string route matchers and to the last element for regular expression matchers.

(defroute "/users/:id" [id query-params]
  (js/console.log (str "User: " id))
  (js/console.log (pr-str query-params)))

(defroute #"/users/(\d+)" [id {:keys [query-params]}]
  (js/console.log (str "User: " id))
  (js/console.log (pr-str query-params)))

;; In both instances...
(secretary/dispatch! "/users/10?action=delete")
;; ... will log
;; User: 10
;; "{:action \"delete\"}"
Humiliating answered 30/9, 2019 at 13:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.