-
Notifications
You must be signed in to change notification settings - Fork 13.7k
Expand file tree
/
Copy pathEmbeddedPreload.tsx
More file actions
79 lines (63 loc) · 2.32 KB
/
Copy pathEmbeddedPreload.tsx
File metadata and controls
79 lines (63 loc) · 2.32 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
70
71
72
73
74
75
76
77
78
79
import { useEndpoint, useMethod, useRouter, useUserId } from '@rocket.chat/ui-contexts';
import { useQuery } from '@tanstack/react-query';
import type { ReactElement, ReactNode } from 'react';
import { useEffect, useMemo } from 'react';
import { RoomsCachedStore, SubscriptionsCachedStore } from '../../../cachedStores';
import { roomsQueryKeys } from '../../../lib/queryKeys';
import { roomCoordinator } from '../../../lib/rooms/roomCoordinator';
import { mapSubscriptionFromApi } from '../../../lib/utils/mapSubscriptionFromApi';
import PageLoading from '../PageLoading';
import { useMainReady } from '../hooks/useMainReady';
const EmbeddedPreload = ({ children }: { children: ReactNode }): ReactElement => {
const ready = useMainReady();
const router = useRouter();
const uid = useUserId();
const roomParams = useMemo(() => {
const routeName = router.getRouteName();
if (!routeName) {
return null;
}
const identifier = roomCoordinator.getRouteNameIdentifier(routeName);
if (!identifier) {
return null;
}
const directives = roomCoordinator.getRoomDirectives(identifier);
if (!directives?.extractOpenRoomParams) {
return null;
}
return directives.extractOpenRoomParams(router.getRouteParameters());
}, [router]);
const getRoomByTypeAndName = useMethod('getRoomByTypeAndName');
const getSubscription = useEndpoint('GET', '/v1/subscriptions.getOne');
const shouldFetch = !!roomParams && !!uid;
const { isLoading } = useQuery({
queryKey: roomParams ? roomsQueryKeys.roomReference(roomParams.reference, roomParams.type, uid ?? undefined) : [],
queryFn: async () => {
if (!roomParams) {
return null;
}
const roomData = await getRoomByTypeAndName(roomParams.type, roomParams.reference);
if (!roomData?._id) {
return null;
}
const subResult = await getSubscription({ roomId: roomData._id });
if (subResult.subscription) {
SubscriptionsCachedStore.upsertSubscription(mapSubscriptionFromApi(subResult.subscription));
}
return subResult;
},
enabled: shouldFetch,
retry: false,
});
useEffect(() => {
if (!shouldFetch || !isLoading) {
SubscriptionsCachedStore.setReady(true);
RoomsCachedStore.setReady(true);
}
}, [shouldFetch, isLoading]);
if (!ready || (shouldFetch && isLoading)) {
return <PageLoading />;
}
return <>{children}</>;
};
export default EmbeddedPreload;