Created
August 28, 2020 07:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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