Skip to content

Instantly share code, notes, and snippets.

@OnurGumus
Forked from pkese/adaptive_demo.fs
Created August 13, 2020 19:23
Show Gist options
  • Save OnurGumus/db10987a0037d94a4e49a4728094682c to your computer and use it in GitHub Desktop.
Save OnurGumus/db10987a0037d94a4e49a4728094682c to your computer and use it in GitHub Desktop.
FSharp.Data.Adaptive sample with React
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