Fork me on GitHub
#re-frame
<
2023-02-02
>
Tema Nomad05:02:13

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

hifumi12306:02:49

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.

p-himik09:02:00

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.

👍 2
Tema Nomad10:02:36

is there an alternative for re-frame-http-fx lib? Or is it the only way to do async ajax requests in clojureScript?

hifumi12310:02:01

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

hifumi12310:02:57

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

p-himik10:02:40

> Or is it the only way to do async ajax requests in clojureScript? From CLJS specifically, you can use anything that JS has. For re-frame, you can always wrap that "anything" in an effect handler.