-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy pathuseSubscribe.ts
More file actions
69 lines (60 loc) · 1.84 KB
/
useSubscribe.ts
File metadata and controls
69 lines (60 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { useEffect } from 'react'
import { EJSON } from 'meteor/ejson'
import { Meteor } from 'meteor/meteor'
import isEqual from 'lodash.isequal'
import remove from 'lodash.remove'
const cachedSubscriptions: Entry[] = []
interface Entry {
params: EJSON[]
name: string
handle?: Meteor.SubscriptionHandle
promise: Promise<void>
result?: null
error?: unknown
}
export function useSubscribeSuspense(name: string, ...params: EJSON[]) {
const cachedSubscription =
cachedSubscriptions.find(x => x.name === name && isEqual(x.params, params))
useEffect(() =>
() => {
setTimeout(() => {
const cachedSubscription =
cachedSubscriptions.find(x => x.name === name && isEqual(x.params, params))
if (cachedSubscription) {
cachedSubscription.handle?.stop()
}
}, 0)
}, [name, EJSON.stringify(params)])
if (cachedSubscription != null) {
if ('error' in cachedSubscription) throw cachedSubscription.error
if ('result' in cachedSubscription) return cachedSubscription.result
throw cachedSubscription.promise
}
const subscription: Entry = {
name,
params,
promise: new Promise<Meteor.SubscriptionHandle>((resolve, reject) => {
const h = Meteor.subscribe(name, ...params, {
onReady() {
subscription.result = null
subscription.handle = h
resolve(h)
},
onStop(error: unknown) {
if (!error) {
remove(cachedSubscriptions,
x =>
x.name === subscription.name &&
isEqual(x.params, subscription.params))
}
subscription.error = error
subscription.handle = h
reject(error)
}
})
})
}
cachedSubscriptions.push(subscription)
throw subscription.promise
}
export const useSubscribe = useSubscribeSuspense