fix: mounted update error

This commit is contained in:
Eric Maciel 2020-10-27 18:29:23 -04:00
parent c6de34b5ef
commit f5d51b3444
2 changed files with 25 additions and 2 deletions

View File

@ -5,14 +5,17 @@ import { Text, Range, Path, NodeEntry } from 'slate'
import { toJS, Cursor, Cursors } from '@hiveteams/collab-bridge'
import { AutomergeEditor } from './automerge-editor'
import useMounted from 'useMounted'
const useCursor = (
e: AutomergeEditor
): { decorate: (entry: NodeEntry) => Range[]; cursors: Cursor[] } => {
const [cursorData, setSursorData] = useState<Cursor[]>([])
const [cursorData, setCursorData] = useState<Cursor[]>([])
const mountedRef = useMounted()
useEffect(() => {
e.onCursor = (data: Cursors) => {
if (!mountedRef.current) return
const ranges: Cursor[] = []
const cursors = toJS(data)
@ -23,7 +26,10 @@ const useCursor = (
}
}
setSursorData(ranges)
// only update state if this component is still mounted
if (mountedRef.current) {
setCursorData(ranges)
}
}
}, [])

View File

@ -0,0 +1,17 @@
import { useRef, useEffect } from 'react'
function useMounted({ onMount = () => {}, onUnmount = () => {} } = {}) {
const isMounted = useRef(false)
useEffect(() => {
isMounted.current = true
onMount()
return () => {
isMounted.current = false
onUnmount()
}
}, [])
return isMounted
}
export default useMounted