Elm Http Init Request

I am new to Elm, but slowly chatting with him. I make some simple Http requests that are successful in all aspects (I get data to display, etc.)

At the moment, I can only get my fetchData to call onClick, I would like to initialize this in init, but I am having problems wrapping my head around this.

.... here is my fetchData function:

fetchData : Cmd Msg fetchData = Http.get repoInfoListDecoder "http://example/api" |> Task.mapError toString |> Task.perform ErrorOccurred DataFetched 

Currently trigger in onClick event view:

 ..... , button [ onClick FetchData ] [ text "Load Data" ] ..... 

I want to avoid requesting data with a button, instead I want the data to load when the application was initialized. Here is my init:

 init = let model = { message = "Welcome", repos = [] } in model ! [] 

And my update (it seems to be deprived ... for example):

 update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of NoOp -> model ! [] ........... FetchData -> { model | message="hi" } ! [fetchData] ........... DataFetched repos -> { model | repos = repos, message = "The data has been fetched!" } ! [] 

It makes sense? I just have difficulty initializing fetchData when the application loads, so I can display my data without clicking a button to get it.

Thanks in advance!

+8
elm
source share
2 answers

When you use Html.program , your init function returns the source data for your model and the command to be executed.

Commands are side effects, such as HTTP requests.

Try changing init to run the command immediately:

 init: (Model, Cmd Msg) init = let model = { message = "Welcome", repos = [] } in model ! [ fetchData ] 
+9
source

Here is a signature like Html.App.program . init accepts Cmd , you just pass your Cmd here.

 program : { init : (model, Cmd msg), update : msg -> model -> (model, Cmd msg), subscriptions : model -> Sub msg, view : model -> Html msg } -> Program Never 
0
source

All Articles