Created
March 8, 2016 16:15
-
-
Save fredcy/fd517aa9173e261e2a3d to your computer and use it in GitHub Desktop.
Example of elm-http-extra getting HTTP response as a String
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 (..) where | |
import Html | |
import Html.Events | |
import Http.Extra | |
import Task | |
import Effects | |
import StartApp | |
type alias Model = | |
{ response : String | |
, error : Maybe (Http.Extra.Error String) | |
} | |
init : ( Model, Effects.Effects Action ) | |
init = | |
( Model "" Nothing, getStringResponse |> Effects.task ) | |
{-| Build a task that will do an HTTP GET and interpret the response body (or | |
error) as a String. | |
-} | |
getStringResponse : Task.Task a Action | |
getStringResponse = | |
let | |
getTask = | |
Http.Extra.get "http://httpbin.org/ip" | |
|> Http.Extra.send Http.Extra.stringReader Http.Extra.stringReader | |
handleError err = | |
Task.succeed <| HttpError err | |
in | |
Task.onError (Task.map (.data >> UpdateResponse) getTask) handleError | |
type Action | |
= NoOp | |
| HttpError (Http.Extra.Error String) | |
| UpdateResponse String | |
update : Action -> Model -> ( Model, Effects.Effects Action ) | |
update action model = | |
case action of | |
NoOp -> | |
( model, Effects.none ) | |
UpdateResponse str -> | |
( { model | response = str }, Effects.none ) | |
HttpError err -> | |
( { model | error = Just err }, Effects.none ) | |
view : Signal.Address Action -> Model -> Html.Html | |
view address model = | |
Html.div | |
[] | |
[ Html.div [] [ Html.text model.response ] | |
, Html.div [] [ Html.text <| toString model.error ] | |
] | |
app : StartApp.App Model | |
app = | |
StartApp.start | |
{ init = init | |
, update = update | |
, view = view | |
, inputs = [] | |
} | |
port tasks : Signal (Task.Task Effects.Never ()) | |
port tasks = | |
app.tasks | |
main : Signal Html.Html | |
main = | |
app.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment