From dd724f0d0e1143e4b89374c65214988232d29f3e Mon Sep 17 00:00:00 2001 From: Juho Teperi Date: Thu, 23 Mar 2023 15:13:27 +0200 Subject: [PATCH] Fix #600: Add frontend function to update query-params for current path --- modules/reitit-frontend/src/reitit/frontend.cljs | 11 +++++++++++ .../reitit-frontend/src/reitit/frontend/easy.cljs | 13 ++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/modules/reitit-frontend/src/reitit/frontend.cljs b/modules/reitit-frontend/src/reitit/frontend.cljs index faa258e0..70dd5482 100644 --- a/modules/reitit-frontend/src/reitit/frontend.cljs +++ b/modules/reitit-frontend/src/reitit/frontend.cljs @@ -88,3 +88,14 @@ match) (do (js/console.warn "missing route" name) nil)))) + +(defn update-path-query-params + "Given Reitit-frontend path, update the query params + with given function and arguments. + + NOTE: coercion is not applied to the query params" + [path f & args] + (let [^goog.Uri uri (Uri/parse path) + new-query (apply f (query-params uri) args)] + (.setQueryData uri (QueryData/createFromMap (clj->js new-query))) + (.toString uri))) diff --git a/modules/reitit-frontend/src/reitit/frontend/easy.cljs b/modules/reitit-frontend/src/reitit/frontend/easy.cljs index 8a76b900..45223817 100644 --- a/modules/reitit-frontend/src/reitit/frontend/easy.cljs +++ b/modules/reitit-frontend/src/reitit/frontend/easy.cljs @@ -2,7 +2,8 @@ "Easy wrapper over reitit.frontend.history, handling the state. Only one router can be active at a time." - (:require [reitit.frontend.history :as rfh])) + (:require [reitit.frontend.history :as rfh] + [reitit.frontend :as rf])) (defonce history (atom nil)) @@ -101,3 +102,13 @@ (rfh/replace-state @history name path-params nil)) ([name path-params query-params] (rfh/replace-state @history name path-params query-params))) + +(defn update-query + "Takes the current location and updates the query params + with given fn and arguments." + [f & args] + ;; TODO: rfh version? + (let [current-path (rfh/-get-path @history) + new-path (apply rf/update-path-query-params current-path f args)] + (.pushState js/window.history nil "" new-path) + (rfh/-on-navigate @history new-path)))