Skip to content

Commit

Permalink
lighter useEffect code
Browse files Browse the repository at this point in the history
  • Loading branch information
jchris committed Jul 22, 2024
1 parent 24b69c5 commit df22d25
Showing 1 changed file with 8 additions and 26 deletions.
34 changes: 8 additions & 26 deletions src/react/useFireproof.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand All @@ -219,10 +215,10 @@ export function useFireproof(name: string | Database = "useFireproof", config: C
query = {},
initialRows: IndexRow<K, T, R>[] = [],
): LiveQueryResult<T, K, R> {
const [result, setResult] = useState({
const [result, setResult] = useState<LiveQueryResult<T, K, R>>(() => ({
rows: initialRows,
docs: initialRows.map((r) => r.doc).filter((r) => r) as DocWithId<T>[],
});
docs: initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r),
}));

const queryString = useMemo(() => JSON.stringify(query), [query]);
const mapFnString = useMemo(() => mapFn.toString(), [mapFn]);
Expand All @@ -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;
Expand All @@ -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;
Expand Down

0 comments on commit df22d25

Please sign in to comment.