Fork me on GitHub
#re-frame
<
2019-05-13
>
lepistane10:05:45

Hope you don't find this too stupid to ask. I've been revising some re-frame docs and the more i read more i am curtain this is wrong 1)

(rf/reg-event-db
 :abc
 validate-spec
 (fn [db [_]]
   (ws/chsk-send! [:abc]
                  3000
                  (fn [reply]
                    (if (sente/cb-success? reply)
                      (rf/dispatch [:success])
                      (println "No reply for abc"))))
   db))
2) and
(do (dispatch [1]) (dispatch [2]...
How can i change this? for 2) it seems that using reg-event-fx and dispatch-n solves that issue but what about the first? Both of these work just fine but i would like to use re-frame properly

shaun-mahood16:05:33

Here's one way you could convert it to use reg-event-fx

shaun-mahood16:05:52

(rf/reg-event-fx
  :abc
  validate-spec
  (fn [_ [event]]
    {:dispatch [:ws-send [event]]}))

(rf/reg-event-fx
  :ws-send
  (fn [_ [_ v]]
    (ws/chsk-send! v
                   3000
                   (fn [reply]
                     (if (sente/cb-success? reply)
                       (rf/dispatch [:success])
                       (println "No reply for " v))))))

👍 1
shaun-mahood16:05:42

You could also use an effect defined by reg-fx as suggested below - I tend to refactor to reg-event-fx first, then to reg-fx later if it makes more sense, though it adds a bit of extra complexity when learning re-frame so it may be worth diving into it a little later.

shaun-mahood16:05:36

The other thing I've realized is that nearly every time I use reg-event-db, at some point later on I wish I had used reg-event-fx - I don't know if this is the case for everyone though.

valtteri11:05:43

Sending message to a websocket is a (side)`effect`. In Re-Frame we aim to keep event-handlers free from side-effects. Side-effects can be extracted to reusable effects. You can define effect handlers with reg-fx. https://github.com/Day8/re-frame/blob/master/docs/Effects.md