web-apis-websharper/Exercises/LocalStorageSync.fs
2025-07-28 01:05:33 -07:00

58 lines
1.7 KiB
Forth

namespace web_api_cookbook.Exercises
open web_api_cookbook
open web_api_cookbook.UI
open web_api_cookbook.UI.Components
open WebSharper
open WebSharper.UI
open WebSharper.UI.Client
open WebSharper.UI.Html
[<JavaScript>]
module LocalStorageSync =
let doc () =
let resetKeyInput, keyInput, keyInputDoc = InputType.text [] "Key: "
let resetValInput, valInput, valInputDoc = InputType.text [] "Value: "
let args = View.Map2 tuple2 keyInput valInput
let clear () =
resetKeyInput ()
resetValInput ()
let onAdd =
fun _ _ (key, value) ->
LocalStorage.setItem key value
clear ()
|> on.clickView args
let addButton = Button.plain [onAdd] "Add Element"
let addedElements =
fun k element ->
let value = View.Map snd element
let onDelete =
fun _ _ ->
LocalStorage.removeItem k
|> on.click
Doc.Concat [
div [] [text <| sprintf "Key: %s" k]
div [] [textView <| View.Map (sprintf "Value: %s") value]
Button.plain [onDelete] "Delete Element"
]
|> Doc.BindSeqCachedViewBy fst <| LocalStorage.view ()
Doc.Concat [
div [] [text "Elements Added to Local Storage:"]
div [attr.``class`` "gridwrap"] [
addedElements
]
div [] [text "Add New Element:"]
div [attr.``class`` "gridwrap"] [
keyInputDoc
valInputDoc
addButton
]
]