/rf-query

A hook-free API to use react-query with re-frame

Primary LanguageClojureMIT LicenseMIT

rf-query

ALPHA STATUS

A hook-free API to use react-query with re-frame.

Installation

io.github.rads/rf-query {:git/tag "v0.0.3" :git/sha "3ec323a"}

Usage

  1. Set up react-query and pass in the useQuery hook to rq/set-config!:
(ns rf-query.example.queries
  (:require [rf-query.core :as rq]
            ["@tanstack/react-query" :refer [useQuery
                                             useMutation
                                             QueryClient
                                             QueryClientProvider]]))

(def query-client (QueryClient.))

(defn provider [props & children]
  [:> QueryClientProvider {:client query-client}
   (into [rq/provider props] children)])

(rq/set-config! {:use-query-fn useQuery
                 :use-mutation-fn useMutation})
  1. Define your query as a map:
(def counter
  {:query-key ["counter"]
   :query-fn (fn [] (js/Promise.resolve (rand-int 100)))})
  1. Use the rq/with-queries function to wrap your component. Access data with the [::rq/query-state query] subscription:
(ns rf-query.example.main
  (:require [cljs.pprint :as pprint]
            [re-frame.core :as rf]
            [reagent.dom :as rdom]
            [rf-query.core :as rq]
            [rf-query.example.queries :as queries]))

(def hello
  (rq/with-queries
    [queries/counter]
    (fn [_]
      (let [query @(rf/subscribe [::rq/query-state queries/counter])
            {:keys [status data error]} query]
        [:div
         [:div (case status
                 :loading "Loading"
                 :error (str "Error: " (.-message error))
                 :success (str "Count: " data))]
         [:pre [:code (with-out-str (pprint/pprint query))]]]))))

(defn app []
  [queries/provider
   [hello]])

(def container (js/document.getElementById "app"))

(defn -main [& _]
  (rdom/render [app] container))

Example

See the rf-query.example namespace.

clojure -M:shadow-cljs watch app
open http://localhost:8888

Roadmap

  • Support additional config options for useQuery