Skip to content

Commit 76943f7

Browse files
committed
Consistent return signature, useRef for subscription
1 parent 879b64d commit 76943f7

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

packages/react-mongo/react-mongo.ts

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,28 @@
11
import { Meteor } from 'meteor/meteor'
22
import { Mongo } from 'meteor/mongo'
33
import { Tracker } from 'meteor/tracker'
4-
import { useEffect, useMemo, useReducer, useState, DependencyList } from 'react'
4+
import {
5+
useEffect,
6+
useMemo,
7+
useReducer,
8+
useRef,
9+
useCallback,
10+
DependencyList,
11+
} from 'react'
512

613
const fur = (x: number): number => x + 1
714
const useForceUpdate = () => useReducer(fur, 0)[1]
815

916
const useSubscriptionClient = (
1017
name: string | false,
1118
args: any[]
12-
): void | Meteor.SubscriptionHandle => {
13-
const [subscription, setSubscription] = useState<Meteor.SubscriptionHandle>()
19+
) => {
20+
const subscription = useRef<Meteor.SubscriptionHandle>()
1421

1522
useEffect(() => {
1623
if (!name) {
17-
return setSubscription( null )
24+
subscription.current = null
25+
return
1826
}
1927

2028
// Use Tracker.nonreactive in case we are inside a Tracker Computation.
@@ -24,14 +32,19 @@ const useSubscriptionClient = (
2432
// it stops the inner one.
2533
const computation = Tracker.nonreactive(() => (
2634
Tracker.autorun(() => {
27-
setSubscription( Meteor.subscribe( name, ...args ) )
35+
subscription.current = Meteor.subscribe( name, ...args )
2836
})
2937
))
3038

3139
return () => computation.stop()
3240
}, [name, ...args])
3341

34-
return subscription
42+
return useCallback(
43+
() => {
44+
return subscription.current?.ready()
45+
},
46+
[name, ...args]
47+
)
3548
}
3649

3750
const useSubscriptionServer = (): Meteor.SubscriptionHandle => ({
Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
import { Meteor } from 'meteor/meteor';
21
import { Mongo } from 'meteor/mongo';
32
import { DependencyList } from 'react';
43
declare type UseSubscriptionOptions = {
54
deps?: DependencyList;
65
updateOnReady?: boolean;
76
};
8-
export declare const useSubscription: (factory: () => Meteor.SubscriptionHandle | void, deps?: DependencyList | UseSubscriptionOptions) => void;
7+
export declare const useSubscription: (name: string | false, args: any[]) => () => boolean;
98
export declare const useCursor: <T = any>(factory: () => Mongo.Cursor<T>, deps?: DependencyList) => Mongo.Cursor<T>;
109
export {};

0 commit comments

Comments
 (0)