From df22d250ebf7cb79b5c03830424eef8cff1f17a0 Mon Sep 17 00:00:00 2001 From: Chris Anderson Date: Mon, 22 Jul 2024 13:31:11 -0700 Subject: [PATCH] lighter useEffect code --- src/react/useFireproof.ts | 34 ++++++++-------------------------- 1 file changed, 8 insertions(+), 26 deletions(-) diff --git a/src/react/useFireproof.ts b/src/react/useFireproof.ts index 2a21d3b2..5773f090 100644 --- a/src/react/useFireproof.ts +++ b/src/react/useFireproof.ts @@ -196,15 +196,11 @@ export function useFireproof(name: string | Database = "useFireproof", config: C useEffect(() => { if (!docId) return; - const unsubscribe = database.subscribe((changes) => { + return database.subscribe((changes) => { if (changes.find((c) => c._id === docId)) { void refreshDoc(); // todo use change.value } }); - - return () => { - unsubscribe(); - }; }, [docId, refreshDoc]); useEffect(() => { @@ -219,10 +215,10 @@ export function useFireproof(name: string | Database = "useFireproof", config: C query = {}, initialRows: IndexRow[] = [], ): LiveQueryResult { - const [result, setResult] = useState({ + const [result, setResult] = useState>(() => ({ rows: initialRows, - docs: initialRows.map((r) => r.doc).filter((r) => r) as DocWithId[], - }); + docs: initialRows.map((r) => r.doc).filter((r): r is DocWithId => !!r), + })); const queryString = useMemo(() => JSON.stringify(query), [query]); const mapFnString = useMemo(() => mapFn.toString(), [mapFn]); @@ -233,15 +229,8 @@ export function useFireproof(name: string | Database = "useFireproof", config: C }, [mapFnString, queryString]); useEffect(() => { - const unsubscribe = database.subscribe(refreshRows); - - return () => { - unsubscribe(); - }; - }, [refreshRows]); - - useEffect(() => { - refreshRows(); + refreshRows(); // Initial data fetch + return database.subscribe(refreshRows); }, [refreshRows]); return result; @@ -260,15 +249,8 @@ export function useFireproof(name: string | Database = "useFireproof", config: C }, [queryString]); useEffect(() => { - const unsubscribe = database.subscribe(refreshRows); - - return () => { - unsubscribe(); - }; - }, [refreshRows]); - - useEffect(() => { - refreshRows(); + refreshRows(); // Initial data fetch + return database.subscribe(refreshRows); }, [refreshRows]); return result;