Created
November 2, 2016 21:34
-
-
Save fredcy/02a2dff9c8990098ae2666993beb480e to your computer and use it in GitHub Desktop.
Http.send example in Elm 0.17
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
module Main exposing (main) | |
import Html | |
import Html.App | |
import Http | |
import Json.Decode as Json exposing ((:=)) | |
import Task exposing (Task) | |
type alias Model = | |
{ error : Maybe Http.RawError | |
, response : Maybe String | |
} | |
type Msg | |
= HttpError Http.RawError | |
| Response Http.Response | |
main = | |
Html.App.program | |
{ init = init | |
, update = update | |
, view = view | |
, subscriptions = subscriptions | |
} | |
init : ( Model, Cmd Msg ) | |
init = | |
-- return the command comprising the Http.send task | |
( Model Nothing Nothing, sendCmd ) | |
sendCmd : Cmd Msg | |
sendCmd = | |
-- convert the Http.send task into a command | |
sendRequest |> Task.perform HttpError Response | |
sendRequest : Task Http.RawError Http.Response | |
sendRequest = | |
let | |
request = | |
{ verb = "GET" | |
, url = "http://httpbin.org/ip" | |
, headers = [] | |
, body = Http.empty | |
} | |
in | |
Http.send Http.defaultSettings request | |
decodeResponse : String -> Result String String | |
decodeResponse responseText = | |
let | |
-- decode the JSON in the response, extracting the "origin" field | |
decoder = | |
("origin" := Json.string) | |
in | |
Json.decodeString decoder responseText | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg |> Debug.log "msg" of | |
HttpError error -> | |
( { model | error = Just error }, Cmd.none ) | |
Response response -> | |
case response.value of | |
Http.Text val -> | |
let | |
ipMaybe = | |
decodeResponse val |> Result.toMaybe | |
in | |
( { model | response = ipMaybe }, Cmd.none ) | |
_ -> | |
( model, Cmd.none ) | |
view : Model -> Html.Html Msg | |
view model = | |
Html.text <| toString model | |
subscriptions : Model -> Sub Msg | |
subscriptions model = | |
Sub.none |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment