1
1
import * as React from 'react' ;
2
+ import { AblyProvider } from '@ably-labs/react-hooks' ;
3
+
2
4
import Spaces , { type Space } from '@ably/spaces' ;
3
5
import { Realtime } from 'ably' ;
4
6
import { nanoid } from 'nanoid' ;
5
7
6
8
import { getSpaceNameFromUrl } from '../utils' ;
7
9
8
- const clientId = nanoid ( ) ;
9
-
10
- export const ably = new Realtime . Promise ( {
11
- authUrl : `/api/ably-token-request?clientId=${ clientId } ` ,
12
- clientId,
13
- } ) ;
14
-
15
- const spaces = new Spaces ( ably ) ;
16
-
17
10
export const SpacesContext = React . createContext < Space | undefined > ( undefined ) ;
18
11
19
12
const SpaceContextProvider : React . FC < { children : React . ReactNode } > = ( { children } ) => {
20
13
const [ space , setSpace ] = React . useState < Space | undefined > ( undefined ) ;
14
+ const spaceName = getSpaceNameFromUrl ( ) ;
15
+
16
+ const [ spaces , ably ] = React . useMemo ( ( ) => {
17
+ const clientId = nanoid ( ) ;
18
+
19
+ const ably = new Realtime . Promise ( {
20
+ authUrl : `/api/ably-token-request?clientId=${ clientId } ` ,
21
+ clientId,
22
+ } ) ;
23
+
24
+ return [ new Spaces ( ably ) , ably ] ;
25
+ } , [ ] ) ;
21
26
22
27
React . useEffect ( ( ) => {
23
- let ignore : boolean = false ;
28
+ let ignore = false ;
24
29
25
30
const init = async ( ) => {
26
- if ( ignore ) {
27
- return ;
28
- }
29
-
30
31
const spaceInstance = await spaces . get ( getSpaceNameFromUrl ( ) , {
31
32
offlineTimeout : 10_000 ,
32
33
} ) ;
33
34
34
- if ( spaceInstance && ! space ) {
35
+ if ( spaceInstance && ! space && ! ignore ) {
35
36
setSpace ( spaceInstance ) ;
36
37
}
37
38
} ;
@@ -41,9 +42,13 @@ const SpaceContextProvider: React.FC<{ children: React.ReactNode }> = ({ childre
41
42
return ( ) => {
42
43
ignore = true ;
43
44
} ;
44
- } ) ;
45
+ } , [ spaceName , spaces ] ) ;
45
46
46
- return < SpacesContext . Provider value = { space } > { children } </ SpacesContext . Provider > ;
47
+ return (
48
+ < AblyProvider client = { ably } >
49
+ < SpacesContext . Provider value = { space } > { children } </ SpacesContext . Provider > { ' ' }
50
+ </ AblyProvider >
51
+ ) ;
47
52
} ;
48
53
49
54
export { SpaceContextProvider } ;
0 commit comments