Created
February 17, 2018 11:19
-
-
Save fswalker/8f23df1d6543672008a9b020f1644472 to your computer and use it in GitHub Desktop.
Example which shows how to fetch, decode and display GitHub licenses in Elm. Ellie link: https://ellie-app.com/xSTPPvrTa1/0
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 as Html exposing (..) | |
import Http as Http | |
import Json.Decode as Decode exposing (Decoder) | |
type alias Model = Maybe (List License) | |
type Msg = | |
UpdateLicenses (Result Http.Error (List License)) | |
type alias License = | |
{ name : String | |
} | |
main : Program Never Model Msg | |
main = | |
Html.program | |
{ init = (Nothing, getGithubLicenses ()) | |
, update = update | |
, view = view | |
, subscriptions = \_ -> Sub.none | |
} | |
update : Msg -> Model -> (Model, Cmd msg) | |
update msg model = | |
case msg of | |
UpdateLicenses (Ok licenses) -> | |
( Just licenses, Cmd.none) | |
UpdateLicenses (Err e) -> | |
( Just [ { name = "Fetching licenses failed" }], Cmd.none ) | |
view : Model -> Html msg | |
view model = | |
div [] | |
[ h1 [] [ text "Github Licenses" ] | |
, ( Maybe.map viewLicenses | |
>> Maybe.withDefault (text "loading licenses...") | |
) model | |
] | |
viewLicense : License -> Html msg | |
viewLicense license = | |
li [] [ text <| .name license ] | |
viewLicenses : List License -> Html msg | |
viewLicenses licenses = | |
if licenses == [] then | |
text "no licenses here" | |
else | |
ul [] (List.map viewLicense licenses) | |
licenseDecoder : Decoder License | |
licenseDecoder = | |
Decode.field "name" Decode.string | |
|> Decode.map License | |
getGithubLicenses : () -> Cmd Msg | |
getGithubLicenses () = | |
let | |
licensesDecoder = | |
Decode.list licenseDecoder | |
request = | |
Http.get "https://api.github.com/licenses" licensesDecoder | |
in | |
Http.send UpdateLicenses request |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment