Skip to content

Instantly share code, notes, and snippets.

@curtiswilkinson
Created July 12, 2017 10:41
Show Gist options
  • Save curtiswilkinson/3c22ad00eb1dfd4cf9877deba549dc86 to your computer and use it in GitHub Desktop.
Save curtiswilkinson/3c22ad00eb1dfd4cf9877deba549dc86 to your computer and use it in GitHub Desktop.
module Main exposing (..)
import Html exposing (..)
import Html.Events exposing (onClick)
import Http
import Json.Decode as Decode
main : Program Never Model Msg
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
type alias Post =
{ userId : Int
, id : Int
, title : String
, body : String
}
type alias Model =
{ posts : List Post
}
type Msg
= Query
| Response (Result Http.Error (List Post))
init : ( Model, Cmd Msg )
init =
( Model [], Cmd.none )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Query ->
( model, getPosts )
Response (Ok posts) ->
( { model | posts = posts }, Cmd.none )
Response (Err _) ->
( model, Cmd.none )
renderPost : Post -> Html Msg
renderPost post =
div []
[ p []
[ strong [] [ text "UserId: " ]
, text (toString post.userId)
]
, p
[]
[ strong [] [ text "Id: " ]
, text (toString post.id)
]
, p
[]
[ strong [] [ text "Title: " ]
, text post.title
]
, p
[]
[ strong [] [ text "Body: " ]
, text post.body
]
]
view : Model -> Html Msg
view model =
div []
[ button [ onClick Query ] [ text "CLICK" ]
, div []
(List.map renderPost model.posts)
]
getPosts : Cmd Msg
getPosts =
let
url =
"https://jsonplaceholder.typicode.com/posts"
in
Http.send Response (Http.get url decodePostList)
decodePost : Decode.Decoder Post
decodePost =
Decode.map4
Post
(Decode.at [ "userId" ] Decode.int)
(Decode.at [ "id" ] Decode.int)
(Decode.at [ "title" ] Decode.string)
(Decode.at [ "body" ] Decode.string)
decodePostList : Decode.Decoder (List Post)
decodePostList =
Decode.list decodePost
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