Last active
August 27, 2024 22:43
-
-
Save pkese/f34c5ac594d846cb42f041627f49f0cd to your computer and use it in GitHub Desktop.
FSharp.Data.Adaptive sample with React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module AdaptiveSample | |
open Fable.React | |
open Fable.React.Props | |
open FSharp.Data.Adaptive | |
let useAdaptive (v: aval<'T>) = | |
// initialize hook with initial value | |
let stateHook = Hooks.useState (AVal.force v) | |
let onChange () = | |
// tell the hook that our value had changed | |
stateHook.update (AVal.force v) | |
let marking = v.AddMarkingCallback onChange | |
Hooks.useEffectDisposable (fun () -> marking) | |
stateHook.current // return initial value | |
let rec getMaxPrime x = | |
let isPrime = function | |
| x when x <= 3 -> true | |
| x when x % 2 = 0 -> false | |
| x -> seq {3..2..x/2} |> Seq.exists (fun d -> x % d = 0) |> not | |
if isPrime x then x else getMaxPrime (x-1) | |
let count = cval 1 | |
let prime = count |> AVal.map getMaxPrime | |
let prime10 = prime |> AVal.map (fun x -> | |
printfn "prime multiplier: %d * 10 = %d" x (x*10) | |
x*10) | |
let PrimeApp = | |
FunctionComponent.Of( fun () -> | |
let _prime = useAdaptive prime | |
let _prime10 = useAdaptive prime10 | |
div [] [ | |
br [] | |
str (sprintf "prime p : p<= count = %d" _prime) | |
br [] | |
str (sprintf "prime p * 10 = %d" _prime10) | |
] | |
) | |
let CounterApp = | |
FunctionComponent.Of( fun () -> | |
let _count = useAdaptive count | |
let showPrimes = Hooks.useState true | |
div [] [ | |
str (sprintf "Current count = %d " (_count)) | |
button [ OnClick (fun _ -> transact (fun () -> count.Value <- count.Value + 1))] [str "+"] | |
p [] [] | |
button [ OnClick (fun _ -> showPrimes.update (not showPrimes.current))] [str "toggle primes"] | |
if showPrimes.current then PrimeApp () else span [] [] | |
] | |
) | |
let view () = | |
CounterApp () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment