Skip to content

Instantly share code, notes, and snippets.

@SirmaXX
Last active August 14, 2019 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SirmaXX/94755105409c356264edcb1d92a28690 to your computer and use it in GitHub Desktop.
Save SirmaXX/94755105409c356264edcb1d92a28690 to your computer and use it in GitHub Desktop.
elm json.decode thanks joelq jessta
[
{
"y": 12,
"x": 12
},
{
"y": 12,
"x": 12
},
{
"y": 12,
"x": 12
},
{
"y": 12,
"x": 12
},
{
"y": 12,
"x": 12
}
]
module Main exposing (Model(..), Msg(..), Point, getCoordinates, init, main, pointDecoder, subscriptions, update, view, viewCoordinates, viewPoint)
import Browser
import Html exposing (div,pre,text,Html,h2)
import Http
import Json.Decode exposing (Decoder, field, float, map2)
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
-- MODEL
type alias Point =
{ x : Float, y : Float }
type Model
= Failure
| Loading
| Success (List Point)
init : () -> ( Model, Cmd Msg )
init _ =
( Loading, getCoordinates )
-- UPDATE
type Msg
= GotGif (Result Http.Error (List Point))
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
GotGif result ->
case result of
Ok url ->
( Success url, Cmd.none )
Err error ->
let
_ =
Debug.log "HTTP ERROR" error
in
( Failure, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
div []
[ h2 [] [ text "coordinates" ]
, viewCoordinates model
]
viewCoordinates : Model -> Html Msg
viewCoordinates model =
case model of
Failure ->
div []
[ text "I could not load a coordinates"
]
Loading ->
text "Loading..."
Success points ->
div []
[ pre [] (List.map viewPoint points)
]
viewPoint : Point -> Html a
viewPoint point =
text <| "x = " ++ String.fromFloat point.x ++ ", y = " ++ String.fromFloat point.y
-- HTTP
getCoordinates : Cmd Msg
getCoordinates =
Http.get
{ url = "http://localhost:5016/data.json"
, expect = Http.expectJson GotGif (Json.Decode.list pointDecoder)
}
pointDecoder : Decoder Point
pointDecoder =
map2 Point
(field "x" float)
(field "y" float)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment