re-frame

domingues 2024-06-24T12:04:06.048409Z

I'd like to know if this approach is possible for a starting event in a card game app ( asking about the dispatchs in :fx ) :

(re-frame/reg-event-fx
 ::start-game
 (fn [{:keys [db]} [_ match]]
   {:db (assoc db :started? true)
    :fx [[:dispatch [::prepare-cards]]
         [:dispatch [::spread-cards]]
         [:dispatch [::get-trump]]
         [:dispatch [::set-player-turn match]]]}))

Kimo 2024-06-24T12:05:51.282969Z

What result do you imagine getting, or not getting?

domingues 2024-06-24T12:07:32.873859Z

Just call these four other events .

domingues 2024-06-24T12:09:31.708739Z

Honestly, I want to know if it is a good approach (or pattern) .

Kimo 2024-06-24T12:12:36.928109Z

It might be a matter of taste. I like composing events this way, sometimes. But if another dev tried to read your project, it might feel more frictional. There's no guarantee that a race won't happen among the effects of subsequent events.

Kimo 2024-06-24T12:14:58.519719Z

The :db effect won't cause a race. But if if that's the only effect, meaning your 4 events are just updating the app-db, then there might be no justification for making 4 separate event handlers. you could just compose 4 helper functions within a single event.

Kimo 2024-06-24T12:17:59.284849Z

If you do have complicated effects that need to be synchronized, consider using something like re-frame-async-flow-fx

p-himik 2024-06-24T12:18:36.016279Z

If a function can be used instead of an event, it should probably be used there. :) Otherwise, it's easy to code yourself into a corner and have fun times debugging race conditions.

domingues 2024-06-24T12:19:08.017719Z

Got it !

Kimo 2024-06-24T12:19:31.365329Z

{:db (-> db start prepare-cards spread-cards get-trump (set-player-turn match))}

👍 1
p-himik 2024-06-24T12:23:37.258619Z

Or, as a commonly discussed pattern here, pass around not db but the full effects map. The only problem with such a solution is that if an event requires a coeffect, you can't really make it into a plain function without making its users know about its needs, somehow. A more involved alternative might be to create a function that retrieves both event handlers and registered interceptors based on event ID, and then combines that all to create a new event handler. But that's not trivial, can't be done without relying on impl details of re-frame, and isn't needed anyway in the vast majority of cases.

domingues 2024-06-24T13:20:52.002509Z

Thanks the for suggestions ! I could decrease the number of event handles from 16 to 5 .

👍 1
2024-07-07T07:50:10.232889Z

> Or, as a commonly discussed pattern here, pass around not db but the full effects map. I have a small library for helping with that. https://github.com/green-coder/mate/blob/made-in-taiwan/test/mate/re_frame_test.cljc#L70-L90

👍 1