Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 27 additions & 22 deletions packages/react-meteor-data/useFind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,24 @@ const fetchData = <T>(cursor: Mongo.Cursor<T>) => {
return data
}

const useSyncEffect = (effect, deps) => {
const [cleanup, timeoutId] = useMemo(
() => {
const cleanup = effect();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deduplicate cleanup calls, GC cleanup function reference, and handle undefined cleanup function:

Suggested change
const cleanup = effect();
let _cleanup = effect();
const cleanup = () => {
if (_cleanup === undefined) return;
_cleanup();
_cleanup = undefined;
};

const timeoutId = setTimeout(cleanup, 1000);
return [cleanup, timeoutId];
},
deps
);

useEffect(() => {
clearTimeout(timeoutId);

return cleanup;
}, [cleanup]);
};


const useFindClient = <T = any>(factory: () => (Mongo.Cursor<T> | undefined | null), deps: DependencyList = []) => {
const cursor = useMemo(() => {
// To avoid creating side effects in render, opt out
Expand All @@ -94,38 +112,25 @@ const useFindClient = <T = any>(factory: () => (Mongo.Cursor<T> | undefined | nu
}
)

// Store information about mounting the component.
// It will be used to run code only if the component is updated.
const didMount = useRef(false)

useEffect(() => {
// Fetch intitial data if cursor was changed.
if (didMount.current) {
if (!(cursor instanceof Mongo.Cursor)) {
return
}

const data = fetchData(cursor)
dispatch({ type: 'refresh', data })
} else {
didMount.current = true
}

useSyncEffect(() => {
if (!(cursor instanceof Mongo.Cursor)) {
return
}

const initialData = fetchData(cursor);
dispatch({ type: 'refresh', data: initialData });

const observer = cursor.observe({
addedAt (document, atIndex, before) {
addedAt(document, atIndex, before) {
dispatch({ type: 'addedAt', document, atIndex })
},
changedAt (newDocument, oldDocument, atIndex) {
changedAt(newDocument, oldDocument, atIndex) {
dispatch({ type: 'changedAt', document: newDocument, atIndex })
},
removedAt (oldDocument, atIndex) {
removedAt(oldDocument, atIndex) {
dispatch({ type: 'removedAt', atIndex })
},
movedTo (document, fromIndex, toIndex, before) {
movedTo(document, fromIndex, toIndex, before) {
dispatch({ type: 'movedTo', fromIndex, toIndex })
},
// @ts-ignore
Expand All @@ -135,7 +140,7 @@ const useFindClient = <T = any>(factory: () => (Mongo.Cursor<T> | undefined | nu
return () => {
observer.stop()
}
}, [cursor])
}, [cursor]);

return cursor ? data : cursor
}
Expand Down