Elm 0.18 Http requests

1.4k views Asked by At

I'm trying to perform a GET Request in elm. The function returns a Task that I am trying to perform. Unfortunately, my reference material is Elm 0.17 and what I have gathered is that the signatur for Task.perform has changed.

fetchTasks: MyModel -> String -> Platform.Task Http.Error (Dict String MyTask)
fetchTasks model apiUrl=
    { method          = "GET"
    , headers         = [ Http.header "Content-Type"  "application/json"
                        , Http.header "Authorization" model.token ]
    , url             = apiUrl
    , body            = Http.emptyBody
    , expect          = Http.expectJson (dict taskDecoder)
    , timeout         = Nothing
    , withCredentials = False    }
    |> Http.request
    |> Http.toTask



fetchTaskCmd : MyModel -> String -> Cmd Msg
fetchTaskCmd model apiUrl =
    Task.perform AuthError GetTasksSuccess <| fetchTasks model apiUrl

This is my function for the GET Request and the command that performs the tasks. The AuthError and GetTasksSuccess are both Messaged that I have defined. What I have read in the Elm Docs that the new signatur for task perform is

perform : (a -> msg) -> Task Never a -> Cmd msg

What do I have to do to implement to get my command working?

1

There are 1 answers

0
Simon H On BEST ANSWER

The changes are bigger than you suggest, with the Http library now working primarily with Commands, and not tasks. So the way to write it now is:

makeRequest model apiUrl=
  Http.request
    { method          = "GET"
    , headers         = [ Http.header "Content-Type"  "application/json"
                        , Http.header "Authorization" model.token ]
    , url             = apiUrl
    , body            = Http.emptyBody
    , expect          = Http.expectJson (dict taskDecoder)
    , timeout         = Nothing
    , withCredentials = False    }




fetchTaskCmd : (Result Error a -> Msg) -> MyModel -> String -> Cmd Msg
fetchTaskCmd msgConstructor model apiUrl =
    Http.send msgConstructor (makeRequest model apiUrl)

If you want to use tokens you might also want to consider using my elm-jwt library to help.