diff --git a/src/index.ts b/src/index.ts index 2a28130..5735db7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,18 @@ -import type {Replicache} from 'replicache'; -import type {ReadonlyJSONValue, ReadTransaction} from 'replicache'; import {useEffect, useState} from 'react'; import {unstable_batchedUpdates} from 'react-dom'; -type Subscribable = Pick; +interface SubscribeOptions { + onData: (data: Data) => void; +} + +type Query = (tx: ReadTransaction) => Promise; + +interface Subscribable { + subscribe: ( + query: Query, + opts: SubscribeOptions, + ) => void; +} // We wrap all the callbacks in a `unstable_batchedUpdates` call to ensure that // we do not render things more than once over all of the changed subscriptions. @@ -22,20 +31,20 @@ function doCallback() { }); } -export function useSubscribe( - rep: Subscribable | null | undefined, - query: (tx: ReadTransaction) => Promise, - def: R, +export function useSubscribe( + rep: Subscribable | undefined | null, + query: Query, + def: Ret, deps: Array = [], -): R { - const [snapshot, setSnapshot] = useState(def); +): Ret { + const [snapshot, setSnapshot] = useState(def); useEffect(() => { if (!rep) { return; } return rep.subscribe(query, { - onData: (data: R) => { + onData: (data: Ret) => { callbacks.push(() => setSnapshot(data)); if (!hasPendingCallback) { void Promise.resolve().then(doCallback);