From e20d60c5d5b4f8296e9b3355436dbfb4cec2684a Mon Sep 17 00:00:00 2001 From: Jordan Marr Date: Sat, 25 Feb 2023 11:56:39 -0500 Subject: [PATCH] Ported `useStore` from Fable.LitStore --- src/Fable.ReactStore/Fable.ReactStore.fs | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/Fable.ReactStore/Fable.ReactStore.fs b/src/Fable.ReactStore/Fable.ReactStore.fs index 2f33009..fdd3b21 100644 --- a/src/Fable.ReactStore/Fable.ReactStore.fs +++ b/src/Fable.ReactStore/Fable.ReactStore.fs @@ -54,6 +54,34 @@ let useStoreLazy (init: unit -> IStore<'Value>): 'Value * StoreUpdate<'Value> = state, fun f -> _store.current.Update(f) +let useStore<'Model>(store: IStore<'Model>) = + // Create placeholder refs with temp defaults (to be replaced with real values from store) + let setModelRef = ref(fun (_: 'Model) -> ()) + let subscriptionRef = ref { new IDisposable with member _.Dispose() = () } + + // Ensure that store subscription is disposed when component is destroyed + useEffect((fun () -> + Dispose(fun () -> subscriptionRef.Value.Dispose() + )), [||]) + + let model, setModel = + useState(fun () -> + + // Susbscribe + let initialModel, subscription = + Store.subscribeImmediate (fun newModel -> + setModelRef.Value newModel + ) store + + // Assign subscription ref (to be disposed with component) + subscriptionRef.Value <- subscription + + initialModel + ) + + setModelRef.Value <- setModel + model + let useElmishStore (init: 'Props -> 'Value * Cmd<'Value, 'Msg>) (update: 'Msg -> 'Value -> 'Value * Cmd<'Value, 'Msg>) (dispose: 'Value -> unit)