Skip to content

Commit

Permalink
feat: useDoc throws when not inside a provider
Browse files Browse the repository at this point in the history
  • Loading branch information
joebobmiles committed Aug 24, 2021
1 parent f1e2711 commit 06fab38
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
5 changes: 3 additions & 2 deletions src/feature/doc/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,24 @@ import * as Y from 'yjs'

import { useDoc } from './hook'

export const DocumentContext = React.createContext<Y.Doc>(new Y.Doc())
export const DocumentContext = React.createContext<Y.Doc | null>(null)

interface DocumentProviderProps {
children: React.ReactNode
doc?: Y.Doc
folderName?: string
documentName?: string
}

export const DocumentProvider = ({
children,
doc = new Y.Doc(),
folderName,
documentName
}: DocumentProviderProps): JSX.Element => {
let superDoc: Y.Doc | null = null
try { superDoc = useDoc() } catch { }

const doc: Y.Doc = new Y.Doc()
if (superDoc !== null) {
superDoc.getMap(folderName ?? '').set(documentName ?? doc.guid, doc)
}
Expand Down
12 changes: 11 additions & 1 deletion src/feature/doc/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,14 @@ import * as Y from 'yjs'

import { DocumentContext } from './component'

export const useDoc = (): Y.Doc => React.useContext(DocumentContext)
export const useDoc = (): Y.Doc => {
const value = React.useContext(DocumentContext)

if (value !== null) {
return value
} else {
throw new Error(
'Could not retrieve a document. Please wrap in a DocumentProvider.'
)
}
}
8 changes: 8 additions & 0 deletions src/feature/doc/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,12 @@ describe('useDoc', () => {
expect(result.current.getSubdocs().size).toBe(1)
expect(Array.from(result.current.getSubdocs().values()).length).toBe(1)
})

it('Throws an error when not inside a DocumentProvider.', () => {
const { result } = renderHook(() => useDoc())

expect(result.error).toEqual(new Error(
'Could not retrieve a document. Please wrap in a DocumentProvider.'
))
})
})

0 comments on commit 06fab38

Please sign in to comment.