Skip to content

Commit

Permalink
lisf from http json
Browse files Browse the repository at this point in the history
  • Loading branch information
maxfarseer committed Feb 16, 2020
1 parent 6347dde commit 756b7ab
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 14 deletions.
4 changes: 2 additions & 2 deletions elm.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
"elm/browser": "1.0.2",
"elm/core": "1.0.5",
"elm/html": "1.0.0",
"elm/http": "2.0.0"
"elm/http": "2.0.0",
"elm/json": "1.1.3"
},
"indirect": {
"elm/bytes": "1.0.8",
"elm/file": "1.0.5",
"elm/json": "1.1.3",
"elm/time": "1.0.0",
"elm/url": "1.0.0",
"elm/virtual-dom": "1.0.2"
Expand Down
50 changes: 38 additions & 12 deletions src/Main.elm
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module Main exposing (main)
import Browser
import Html exposing (Html, div, h1, li, text, ul)
import Http
import Json.Decode as JD exposing (Decoder, at, field, list, string)


type alias Fruit =
Expand All @@ -14,7 +15,7 @@ type alias Fruit =
type FruitsRequest
= Loading
| Failure
| Success
| Success (List Fruit)


type alias Model =
Expand All @@ -26,13 +27,13 @@ init _ =
( { fruits = Loading }
, Http.get
{ url = "http://my-json-server.typicode.com/maxfarseer/elm-webinar-2/fruits"
, expect = Http.expectString GotFruits
, expect = Http.expectJson GotFruits fruitsDecoder
}
)


type Msg
= GotFruits (Result Http.Error String)
= GotFruits (Result Http.Error (List Fruit))


update : Msg -> Model -> ( Model, Cmd Msg )
Expand All @@ -41,13 +42,29 @@ update msg model =
GotFruits response ->
case response of
Ok fruits ->
( { model | fruits = Success }, Cmd.none )
( { model | fruits = Success fruits }, Cmd.none )

Err _ ->
( { model | fruits = Failure }, Cmd.none )


renderItem : Fruit -> Html msg

-- Decoders


fruitsDecoder : Decoder (List Fruit)
fruitsDecoder =
list decodeFruit


decodeFruit : Decoder Fruit
decodeFruit =
JD.map2 Fruit
(field "name" string)
(field "emoji" string)


renderItem : Fruit -> Html Msg
renderItem fruit =
li [] [ text (fruit.emoji ++ " " ++ fruit.name) ]

Expand All @@ -61,14 +78,23 @@ renderFruits data =
ul [] list


view : Model -> Html msg
view : Model -> Html Msg
view model =
div []
[ h1 []
[ text "Сезон фруктов!" ]

--, renderFruits model.fruits
]
case model.fruits of
Success fruits ->
div []
[ h1 []
[ text "Сезон фруктов!" ]
, renderFruits fruits
]

Loading ->
div []
[ text "Загружаю" ]

Failure ->
div []
[ text "Во время загрузки, произошла ошибка" ]


main : Program () Model Msg
Expand Down

0 comments on commit 756b7ab

Please sign in to comment.