Created
July 12, 2017 10:41
-
-
Save curtiswilkinson/3c22ad00eb1dfd4cf9877deba549dc86 to your computer and use it in GitHub Desktop.
Get Posts example: https://ellie-app.com/3JQS9n8RPCfa1/4
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 (..) | |
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