Skip to content

Commit

Permalink
🩹 fix(useSubscription): Disable stale handles callbacks.
Browse files Browse the repository at this point in the history
  • Loading branch information
make-github-pseudonymous-again committed Jul 11, 2024
1 parent 2914031 commit a57fe4e
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions imports/api/publication/useSubscription.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
import {Meteor} from 'meteor/meteor';
import {Tracker} from 'meteor/tracker';
import {useState, useEffect} from 'react';
import {useState, useEffect, useRef} from 'react';

import useChanged from '../../ui/hooks/useChanged';

import type Args from '../Args';

import subscribe from './subscribe';
import type Publication from './Publication';
import type SubscriptionHandle from './SubscriptionHandle';

const useSubscriptionClient = <A extends Args>(
publication?: Publication<A> | null,
...args: A
): (() => boolean) => {
const [loading, setLoading] = useState(true);
const handleRef = useRef<SubscriptionHandle | null>(null);

const deps = [setLoading, publication, JSON.stringify(args)];

useEffect(() => {
if (!publication) return undefined;
const setNotLoading = () => {
setLoading(false);
if (handleRef.current === handle) setLoading(false);
};

const callbacks = {
Expand All @@ -28,15 +30,18 @@ const useSubscriptionClient = <A extends Args>(
onError: setNotLoading,
};

const computation = Tracker.nonreactive(() =>
Tracker.autorun(() => {
if (publication) subscribe(publication, ...args, callbacks);
}),
);
const handle = subscribe(publication, ...args, callbacks);
handleRef.current = handle;

// NOTE `setLoading(true)` is called:
// - on first execution,
// - on subsequent executions, if the subscription is not ready yet
// (e.g. double-render in strict mode in development, concurrent mode)
// - when restarting a stopped or errored subscription
setLoading(!handle.ready());

Check warning on line 41 in imports/api/publication/useSubscription.ts

View check run for this annotation

Codecov / codecov/patch

imports/api/publication/useSubscription.ts#L41

Added line #L41 was not covered by tests

// Stop the computation on when publication changes or unmount.
return () => {
computation.stop();
handle.stop();
};
}, deps);

Expand Down

0 comments on commit a57fe4e

Please sign in to comment.