Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created August 28, 2020 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hubgit/91b694793fb49ce4b6a6ece887bc7c57 to your computer and use it in GitHub Desktop.
Save hubgit/91b694793fb49ce4b6a6ece887bc7c57 to your computer and use it in GitHub Desktop.
A React context provider with undefined default value that exports a hook for accessing the context value
import { EditorState } from 'prosemirror-state'
import { EditorView } from 'prosemirror-view'
import React, { createContext, useContext, useEffect, useState } from 'react'
import { Editor } from '../Editor'
const EditorContext = createContext<EditorState | undefined>(undefined)
export const useEditorContext = () => {
const editor = useContext(EditorContext)
if (!editor) {
throw new Error('Editor context is only available inside EditorProvider')
}
return editor
}
export const EditorProvider: React.FC<{ editor: Editor }> = ({ editor, children }) => {
const [state, setState] = useState<EditorState>(editor.view.state)
useEffect(() => {
const handler = (event: Event) => {
setState((event as CustomEvent<EditorState>).detail)
}
editor.addEventListener('statechange', handler)
return () => {
editor.removeEventListener('statechange', handler)
}
}, [editor])
return (
<EditorContext.Provider value={state}>{children}</EditorContext.Provider>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment