/
Main.elm
149 lines (115 loc) · 3.15 KB
/
Main.elm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
module Components.Examples.Http.Main exposing (main)
import Browser
import Html exposing (Html, button, div, input, text)
import Html.Attributes exposing (disabled, value)
import Html.Events exposing (onClick, onInput)
import Http
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline as Decode
import Json.Encode as Encode
type alias Model =
{ input : String
, status : Status
}
type Msg
= InputText String
| SubmitTodo
| GotResponse (Result Http.Error Todo)
type alias Todo =
{ id : Int
, title : String
, completed : Bool
}
type Status
= Idle
| Running
| Success Todo
| Failure
decodeTodo : Decoder Todo
decodeTodo =
Decode.succeed Todo
|> Decode.required "id" Decode.int
|> Decode.required "title" Decode.string
|> Decode.required "completed" Decode.bool
encodeTodo : Todo -> Encode.Value
encodeTodo todo =
Encode.object
[ ( "id", Encode.int todo.id )
, ( "title", Encode.string todo.title )
, ( "completed", Encode.bool todo.completed )
]
main : Program () Model Msg
main =
Browser.element
{ init = \_ -> init
, update = update
, view = view
, subscriptions = \_ -> Sub.none
}
init : ( Model, Cmd Msg )
init =
( { input = ""
, status = Idle
}
, Cmd.none
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
InputText input ->
( { model | input = input }, Cmd.none )
SubmitTodo ->
( { model | status = Running }, submitTodo model.input )
GotResponse (Result.Ok todo) ->
( { model | status = Success todo }
, Cmd.none
)
GotResponse (Result.Err err) ->
( { model | status = Failure }
, Cmd.none
)
view : Model -> Html Msg
view model =
div []
[ input [ value model.input, onInput <| InputText ] []
, button
[ disabled <| model.status == Running
, onClick SubmitTodo
]
[ text <| submitButtonText model.status ]
, div []
[ case model.status of
Success todo ->
encodeTodo todo |> Encode.encode 4 |> text
Running ->
text <| "No response yet"
Idle ->
text <| "No response yet"
Failure ->
text <| "Error"
]
]
submitButtonText : Status -> String
submitButtonText status =
case status of
Idle ->
"Add Todo"
Running ->
"Adding..."
Success _ ->
"Added!"
Failure ->
"Failed!"
submitTodo : String -> Cmd Msg
submitTodo input =
Http.post
{ url = "https://jsonplaceholder.typicode.com/todos"
, body =
Http.jsonBody
(Encode.object
[ ( "title", Encode.string input )
, ( "completed", Encode.bool False )
]
)
, expect = Http.expectJson GotResponse decodeTodo
}