Apply query parameters encoding on rfe/set-query

This commit is contained in:
Juho Teperi 2025-01-22 11:10:39 +02:00
parent 21e5840f13
commit 1ba77a7267
2 changed files with 10 additions and 5 deletions

View file

@ -289,13 +289,18 @@
New query params can be given as a map, or a function taking
the old params and returning the new modified params.
Note: The query parameter values aren't coereced, so the
update fn will see string values for all query params."
The current path is matched against the routing tree, and the match data
(schema, coercion) is used to encode the query parameters."
([history new-query-or-update-fn]
(set-query history new-query-or-update-fn nil))
([history new-query-or-update-fn {:keys [replace] :as opts}]
(let [current-path (-get-path history)
new-path (rf/set-query-params current-path new-query-or-update-fn)]
;; FIXME: What if there is no match?
match (rf/match-by-path (.-router history) current-path)
query-params (if (fn? new-query-or-update-fn)
(new-query-or-update-fn (:query (:parameters match)))
new-query-or-update-fn)
new-path (rf/match->path match query-params (:fragment (:parameters match)))]
(if replace
(.replaceState js/window.history nil "" (-href history new-path))
(.pushState js/window.history nil "" (-href history new-path)))

View file

@ -69,11 +69,11 @@
;; 2. /bar/2?a=1
6 (do (is (= "/bar/2?a=1" url)
"update-query with map")
(rfe/set-query #(assoc % :b "foo") {:replace true}))
(rfe/set-query #(assoc % :q "x") {:replace true}))
;; 0. /
;; 1. /bar/2
;; 2. /bar/2?a=1&b=foo
7 (do (is (= "/bar/2?a=1&b=foo" url)
7 (do (is (= "/bar/2?a=1&q=__x" url)
"update-query with fn")
(.go js/window.history -2))
;; 0. /