Reputation: 1995
In my Elm app, there is a parent and a child. I would like the child to send an HTTP command and then the parent would update it on the fly by adding the backend config that the child model doesn't have.
The way I see it is:
I would like to implement HTTP actions in children modules so my app remains modular while keeping the config in one place.
Any help is welcome. Maybe a different approach can solve my problem too!
Upvotes: 2
Views: 996
Reputation: 2923
Keep all the configuration details in a module that handles the Http Requests. For example, you can have this code in Requests.elm
import Http
import Task
url = "http://ip.jsontest.com/"
getIP : (String -> msg) -> Cmd msg
getIP tagger =
Http.getString url
|> Task.perform (\e -> tagger (toString e)) tagger
and then in the Component code have something like
update msg model =
case msg of
GetIP -> model ! [Requests.getIP ShowIP]
ShowIP str -> {model | ipStr = str} ! []
all the configuration details are hidden from the component. Only an API of access is exposed.
LATER EDIT:
Another option would be to define and pass around a dynamic Context. You can manage this context at the top level and just pass the current version around when you update things. It would look like this
In Requests.elm
import Http
import Task
type alias Context =
{ url : String }
getIP : Context -> (String -> msg) -> Cmd msg
getIP ctx tagger =
Http.getString ctx.url
|> Task.perform (\e -> tagger (toString e)) tagger
in Components:
update ctx msg model =
case msg of
GetIP -> model ! [Requests.getIP ctx ShowIP]
ShowIP str -> {model | ipStr = str} ! []
Upvotes: 2