Last active
March 4, 2018 18:23
-
-
Save jsmesami/2836b97cf1323d56aee807ee10dd2fcf to your computer and use it in GitHub Desktop.
Useful Re-frame event handler for doing JSON XHR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns net.json-xhr | |
(:require | |
[ajax.core :as ajax] | |
[day8.re-frame.http-fx] | |
[re-frame.core :refer [reg-event-fx trim-v]] | |
(defn default-success-fx | |
[db response] | |
{:db db}) ;; You can define some useful default effects here | |
(defn default-failure-fx | |
[db response] | |
{:db db}) ;; You can define some useful default effects here | |
(reg-event-fx | |
:net/json-xhr | |
[trim-v] | |
(fn [_ [method uri & {:keys [data success-fx failure-fx timeout] | |
:or {data {} | |
success-fx default-success-fx | |
failure-fx default-failure-fx | |
timeout 8000}}]] | |
{:http-xhrio {:method method | |
:uri uri | |
:timeout timeout | |
:params data | |
:format (ajax/json-request-format) | |
:response-format (ajax/json-response-format {:keywords? true}) | |
:on-success [:net/success success-fx] | |
:on-failure [:net/failure failure-fx]}})) | |
(reg-event-fx | |
:net/success | |
[trim-v] | |
(fn [{:keys [db]} [success-fx response]] | |
(success-fx db (js->clj response)))) | |
(reg-event-fx | |
:net/failure | |
[trim-v] | |
(fn [{:keys [db]} [failure-fx response]] | |
(failure-fx db (js->clj response)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment