I am new to Elm and am currently experimenting with receiving data from a server. I am also new to programming WebApps which is why I am having a hard time to formulate my problem.
What I want to achieve is
- press button
- get a value from server (“multiplier”)
- update model field with that value
- trigger calculation using the multiplier and upate model field “result”
However, I am not able to achieve this. My below code works. But I use a workaround and don’t use the model field result
for storing the result of calcResult
.
My question is, however, how can I update the model field result
when pressing the button and at the same time also get the server data.
module NPV exposing (..)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput)
import Http
type alias Model =
{initialState : Bool
, value : Maybe Float
, multiplier : Maybe Float
, result : Maybe Float
}
initialModel : Model
initialModel =
{initialState = True
, value = Just 0
, multiplier = Just 0
, result = Nothing
}
type Msg =
GetValue String
| PressedOk
| ReceiveMultiplier (Result Http.Error String)
url : String
url =
"http://localhost:8989/multiplier"
getMultiplier : Cmd Msg
getMultiplier =
Http.get
{ url = url
, expect = Http.expectString ReceiveMultiplier
}
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
GetValue inputValue ->
({model | value = String.toFloat inputValue}, Cmd.none)
PressedOk ->
({model | initialState = False}, getMultiplier)
ReceiveMultiplier result ->
case result of
Ok value ->
({model | multiplier = String.toFloat value}, Cmd.none)
Err error ->
(model, Cmd.none)
viewResultOrError : Model -> Html Msg
viewResultOrError model =
if model.initialState == True then
viewInitial
else
case (model.value, model.multiplier) of
(Just v, Just m) ->
viewResult (v*m)
_ ->
viewError
viewError : Html Msg
viewError =
div [][text "Ups, something went wrong!"]
viewResult : Float -> Html Msg
viewResult value =
div [][text ("Input * Multiplier is: " ++ (value |> Debug.toString))]
viewInitial : Html Msg
viewInitial =
div [][]
view : Model -> Html Msg
view model =
div [][h2 [] [text "My first Webapp"]
, input [placeholder "Give me your value", onInput GetValue][]
, button [onClick PressedOk][text "OK"]
, viewResultOrError model
, div [][h3 [][text "Debug"]
, text (Debug.toString model)
]
]
calcResult : Maybe Float -> Maybe Float -> Maybe Float
calcResult value multiplier =
case (value, multiplier) of
(Just a, Just b) ->
Just (a * b)
(_,_) ->
Nothing
main : Program () Model Msg
main =
Browser.element
{init = \flags -> (initialModel, Cmd.none)
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
Thanks for your help!