From 9d1f4a03ee5a97a1d1d3f9a8f88428355ef43230 Mon Sep 17 00:00:00 2001 From: Aaron Boodman Date: Sat, 12 Nov 2022 16:47:09 -1000 Subject: [PATCH] chore: specify types needed directly. I'm not sure getting them through v10 of Replicache was doing the right thing. When I install replicache-react and replicache v12 together in an app, I only see one version of replicache, v12. And replicache-react doesn't re-include the required types in its own .d.ts file. So unless tsc is being very fancy (which, I dunno, maybe it is) and getting the old version of replicache behind the scenes somehow, then I think this is using the wrong types. Anyway, this is more direct way to do what was meant. --- src/index.ts | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) 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);