This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2023-02-02
Channels
- # announcements (3)
- # asami (29)
- # babashka (62)
- # beginners (131)
- # biff (7)
- # calva (31)
- # cider (5)
- # clerk (14)
- # clj-kondo (3)
- # cljsrn (12)
- # clojars (18)
- # clojure (72)
- # clojure-austin (17)
- # clojure-dev (6)
- # clojure-europe (31)
- # clojure-indonesia (1)
- # clojure-nl (1)
- # clojure-norway (18)
- # clojure-sweden (11)
- # clojure-uk (6)
- # clr (47)
- # conjure (42)
- # cursive (88)
- # datalevin (2)
- # datomic (25)
- # emacs (42)
- # exercism (1)
- # fulcro (10)
- # funcool (8)
- # gratitude (2)
- # honeysql (16)
- # introduce-yourself (5)
- # jobs-discuss (26)
- # leiningen (5)
- # lsp (31)
- # malli (21)
- # matcher-combinators (14)
- # missionary (2)
- # nbb (1)
- # off-topic (40)
- # pathom (38)
- # portal (2)
- # re-frame (7)
- # reagent (18)
- # reitit (1)
- # releases (5)
- # shadow-cljs (62)
- # sql (12)
- # testing (4)
- # xtdb (37)
What is the best practice for ajax-requests in re-frame?
For example, so to initialize todos array from API GET /api/todos
?
I have :initialize
event
And I see 2 ways:
First way
To add coeffect via inject-cofx
:
(re-frame/reg-cofx
:todos-from-api
(fn [cofx _]
(assoc cofx :todos-from-api
(into (sorted-map)
HERE I MAKE AJAX REQUEST via cljs-ajax))))
Second way
To add re-frame-http-fx
lib and use it right inside the event:
(reg-event-fx
:initialize
(fn [{:keys [db]} _]
{:db (assoc default-db :todos something)
:http-xhrio {:method :get
:uri ""
:response-format (ajax/json-response-format {:keywords? true})
:on-success [:good-http-result] ;; <--- new reg-event-db
:on-failure [:bad-http-result]}})) ;; <--- new reg-event-db too
The second option is the easiest one imo. You can add e.g. a :loading
key to the db then you create event handlers for the API request when it succeeds and fails.
Indeed, the second approach makes the most sense. And the first approach can't even be implemented because you can't make a synchronous AJAX request. And a coeffect can't be async.
is there an alternative for re-frame-http-fx
lib? Or is it the only way to do async ajax requests in clojureScript?
You could make your own coeffects that use other libraries like fetch or cljs-http, but I’ve found re-frame-http-fx
to just be the most convenient since it’s very easy to set up
basically, the library already has ajax set up in a good way with re-frame, whereas with other things (fetch, cljs-http, …), you will either have to set up cofx yourself or rely on lesser used libraries like https://github.com/superstructor/re-frame-fetch-fx