Skip to content

Commit

Permalink
feat: all providers are now singletons
Browse files Browse the repository at this point in the history
  • Loading branch information
joebobmiles committed Aug 24, 2021
1 parent 938636d commit 57480f4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 12 deletions.
26 changes: 22 additions & 4 deletions src/feature/provider/hook/useIndexedDb.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,31 @@
import React from 'react'
import { IndexeddbPersistence } from 'y-indexeddb'
import { useDoc } from '../../doc'

import { useDoc, useProviders } from '../../doc'

export const useIndexedDb = (name: string): IndexeddbPersistence => {
const doc = useDoc()
const providers = useProviders()

return React.useMemo(
const existingProvider = React.useMemo(
() =>
new IndexeddbPersistence(name, doc),
[name]
Array.from(providers.values())
.find((provider): provider is IndexeddbPersistence =>
provider instanceof IndexeddbPersistence && provider.db?.name === name
),
[providers, name]
)

if (existingProvider !== undefined) {
return existingProvider
} else {
const provider = React.useMemo(
() => new IndexeddbPersistence(name, doc),
[doc, name]
)

providers.add(provider)

return provider
}
}
31 changes: 23 additions & 8 deletions src/feature/provider/hook/useWebSocket.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,36 @@
import React from 'react'
import { WebsocketProvider } from 'y-websocket'

import { useDoc } from '../../doc'
import { useDoc, useProviders } from '../../doc'

export const useWebSocket = (
url: string,
room: string
): WebsocketProvider => {
const doc = useDoc()
const providers = useProviders()

return React.useMemo(
const existingProvider = React.useMemo(
() =>
new WebsocketProvider(
url,
room,
doc
),
[url, room]
Array.from(providers.values())
.find((provider): provider is WebsocketProvider =>
provider instanceof WebsocketProvider &&
provider.url === url &&
provider.roomname === room
),
[providers, url, room]
)

if (existingProvider !== undefined) {
return existingProvider
} else {
const provider = React.useMemo(
() => new WebsocketProvider(url, room, doc),
[doc, url, room]
)

providers.add(provider)

return provider
}
}

0 comments on commit 57480f4

Please sign in to comment.