Created
January 4, 2023 15:46
-
-
Save ChristophP/d5c8d84fff86b255a51bea06d0ff8f9f to your computer and use it in GitHub Desktop.
Example of the effects pattern in Elm
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
port module Effects exposing (Effect(..), toCmd) | |
import Api | |
import Browser.Dom as Dom | |
import Browser.Navigation as Nav | |
import Date exposing (Date) | |
import Json.Encode as JE | |
import Task | |
port callDomMethod : { id : String, method : String, args : List JE.Value } -> Cmd msg | |
type Effect msg | |
= None | |
| Batch (List (Effect msg)) | |
| Http (Api.Request msg) | |
| ShowSuccessMessage String | |
| ShowErrorMessage String | |
| GetToday (Date -> msg) | |
| Navigate String | |
| ReplaceUrl String | |
| ShoelaceFocus String | |
type alias Config = | |
{ apiConfig : Api.Config | |
, navKey : Nav.Key | |
} | |
toCmd : Config -> Effect msg -> Cmd msg | |
toCmd ({ apiConfig, navKey } as config) effect = | |
case effect of | |
None -> | |
Cmd.none | |
Batch effects -> | |
Cmd.batch (List.map (toCmd config) effects) | |
Http req -> | |
Api.toHttpCmd apiConfig req | |
ShowSuccessMessage body -> | |
callDomMethod | |
{ id = "message-toast" | |
, method = "showSuccessMessage" | |
, args = [ JE.string body ] | |
} | |
ShowErrorMessage body -> | |
callDomMethod | |
{ id = "message-toast" | |
, method = "showErrorMessage" | |
, args = [ JE.string body ] | |
} | |
GetToday toMsg -> | |
Task.perform toMsg Date.today | |
Navigate url -> | |
Nav.pushUrl navKey url | |
ReplaceUrl url -> | |
Nav.replaceUrl navKey url | |
ShoelaceFocus id -> | |
callDomMethod | |
{ id = id | |
, method = "setFocus" | |
, args = [] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment