From 57480f412431c86479fb8bd4a6adf9c6d6c9be97 Mon Sep 17 00:00:00 2001 From: Joseph R Miles Date: Tue, 24 Aug 2021 14:37:07 -0700 Subject: [PATCH] feat: all providers are now singletons --- src/feature/provider/hook/useIndexedDb.ts | 26 ++++++++++++++++--- src/feature/provider/hook/useWebSocket.ts | 31 +++++++++++++++++------ 2 files changed, 45 insertions(+), 12 deletions(-) diff --git a/src/feature/provider/hook/useIndexedDb.ts b/src/feature/provider/hook/useIndexedDb.ts index ca0ff97..7330f9c 100644 --- a/src/feature/provider/hook/useIndexedDb.ts +++ b/src/feature/provider/hook/useIndexedDb.ts @@ -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 + } } diff --git a/src/feature/provider/hook/useWebSocket.ts b/src/feature/provider/hook/useWebSocket.ts index 11ae5f9..3a32e87 100644 --- a/src/feature/provider/hook/useWebSocket.ts +++ b/src/feature/provider/hook/useWebSocket.ts @@ -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 + } }