Skip to content

Instantly share code, notes, and snippets.

@mrb

mrb/Main.elm

Created Sep 9, 2016
Embed
What would you like to do?
Tips
module Main exposing (..)
import Html exposing (Html, div, button, text, img, br, p)
import Html.Attributes exposing (src)
import Html.Events exposing (onClick)
import Html.App
import Http
import Task exposing (Task)
import Json.Decode as Decode exposing (Decoder(..), string, (:=), succeed, list)
import Extra exposing ((|:))
-- MODEL
type alias Model =
List Tip
init : ( Model, Cmd Msg )
init =
( [], fetchCmd )
-- MESSAGES
type Msg
= Fetch
| FetchSuccess (List Tip)
| FetchError Http.Error
type alias Tip =
{ title : String
, date : String
, tags : String
, image : String
, thumbnail : String
}
-- VIEW
view : Model -> Html Msg
view model =
div []
(List.map
(\x ->
div []
[ text x.title
, p [] []
, img [ src x.thumbnail ] []
]
)
(List.filter (\x -> (x.tags == "food")) model)
)
decodeTip : Decode.Decoder Tip
decodeTip =
Decode.succeed Tip
|: ("title" := string)
|: ("date" := string)
|: ("tags" := string)
|: ("image" := string)
|: ("thumbnail" := string)
decode : Decode.Decoder (List Tip)
decode =
Decode.list decodeTip
url : String
url =
"https://api.myjson.com/bins/498wk"
fetchTask : Task Http.Error (List Tip)
fetchTask =
Http.get decode url
fetchCmd : Cmd Msg
fetchCmd =
Task.perform FetchError FetchSuccess fetchTask
-- UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Fetch ->
( model, fetchCmd )
FetchSuccess tips ->
( tips, Cmd.none )
FetchError error ->
( [ { title = (toString error), date = "", tags = "", image = "", thumbnail = "" } ], Cmd.none )
-- MAIN
main : Program Never
main =
Html.App.program
{ init = init
, view = view
, update = update
, subscriptions = (always Sub.none)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment