Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax GET with Reagent

I am doing an Ajax GET from my Reagent application, to load some stuff from the database.

I am not entirely sure what is the best way of getting the result of such ajax call to my page, considering that if I put it in an atom, then Reagent automatically re-renders a component when an atom is dereferenced, which means I get an infinite sequence of ajax calls.

For some code,

(def matches (atom nil))

(defn render-matches [ms]
  (reset! matches (into [:ul] (map (fn [m] ^{:key m}[:li m])
                                   (walk/keywordize-keys (t/read (t/reader :json) ms)))))

This function basically creates a [:ul [:li "Stuff here"] [:li "And here"]]

Which i would like displayed on my page, which now has the following code.

(defn standings-page []
  (GET "/list-matches"
       {:handler render-matches})
  @matches)
like image 644
Helios Avatar asked May 05 '15 18:05

Helios


People also ask

How to call GET method in AJAX?

Syntax: $.get(URL,callback); The required URL parameter specifies the URL you wish to request. The optional callback parameter is the name of a function to be executed if the request succeeds.

What is the difference between AJAX GET and POST?

Basically the difference between GET and POST is that in a GET request, the parameters are passed in the URL where as in a POST, the parameters are included in the message body. Save this answer.

How can I get response data from Ajax call?

You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.


1 Answers

I think it's better to save only data in an atom and to generate the HTML as part of the component logic.

Also it's better to trigger the AJAX call outside the render phase, for example, before the component will mount, or as the result of an event (on-click on a button for example).

Like this:

(def matches (atom nil))
(defn component []
  (let [get-stuff (fn [] (GET "/..." :handler (fn [response] 
                           (reset! matches (:body response))))]
    (get-stuff) <-- called before component mount
    (fn []
      [:ul
        (for [m match]
          ^{:key ...} 
          [:li ...])])))

This is called form-2 in this post.

like image 134
Michiel Borkent Avatar answered Nov 09 '22 05:11

Michiel Borkent