I finished loading resources from an API in Elm, everything is fine... except for one litte problem : I don't know how to update or create a new record without persisting it.
I have a type Msg (I striped some code for this demo)
type Msg
= NoOp
| FetchSucceed (List User)
| FetchError Http.Error
| UpdateTitle String
| ...
update msg model =
case model of
NoOp ->
( model, Cmd.none )
FetchSucceed newModel =
( { model | users = newModel, isLoading = False }, Cmd.none )
FetchError _ =
( { model | isLoading = False }, Cmd.none )
UpdateTitle newTitle =
-- I don't know what to put here, the previous messages
-- have a list, and I Just want to add ONE model
view model =
div []
[ List.map displayRow model.users
, formCreateUser {title = "", username = "", email = ""}
]
formCreateUser user =
div []
[ input [ onInput UpdateTitle, placeholder "Title" ] []
, button [ onClick SaveUser ] [ text "Save" ]
]
I would love to be able to add a new model from this form (formCreateUser), but I keep getting this error :
The 3rd element has this type:
VirtualDom.Node Msg
But the 4th is:
Html Link -> Html (String -> Msg)
edit2: Add some context
答案 0 :(得分:2)
如果我了解您的示例代码段,则您有一个显示现有用户列表的页面,并且您希望快速添加"快速添加"允许您创建仅给定标题的另一个用户的表单。我将举例说明如何实现这一目标,希望能够对您遇到的问题有所了解。
我假设您的用户和模型目前看起来像这样:
type alias Model =
{ users : List User
, isLoading : Bool
, newUserTitle : Maybe String
}
由于您有快速添加表单,因此我不认为您希望在新用户点击提交之前附加新用户。考虑到这一概念,让我们更新Model以存储待处理的新用户标题:
formCreateUser
现在我们可以相应地更改您的视图功能。由于我们要在文本框中显示已键入的标题,因此我们将formCreateUser model =
div []
[ input [ onInput UpdateTitle, placeholder "Title", value (Maybe.withDefault "" model.newUserTitle) ] []
, button [ onClick SaveUser ] [ text "Save" ]
]
更改为:
view
这意味着view model =
div []
[ div [] (List.map displayRow model.users)
, formCreateUser model
]
中的调用代码也需要更新:
UpdateTitle
现在我们需要处理 UpdateTitle newTitle ->
( { model | newUserTitle = Just newTitle }, Cmd.none )
Msg来设置输入的内容:
SaveUser ->
case model.newUserTitle of
Nothing -> (model, Cmd.none)
Just title ->
( { model
| newUserTitle = Nothing
, users = model.users ++ [{ title = title, username = "", email = "" }]
}, Cmd.none)
现在我们也可以处理提交按钮了。您可以在此处创建新用户并将其附加到现有用户列表中:
SaveUser
如果您希望Cmd
将其提交到API端点,您还会返回适当的{{1}},但这似乎超出了您的问题范围。
虽然这并不是处理您情况的理想方式,但希望这些解释能让您更好地理解此类事物所需的构建块。我已发布full gist here,可以粘贴并在elm-lang.org/try中投放。