mirror of
https://github.com/cudr/slate-collaborative.git
synced 2024-10-27 20:34:06 +00:00
fix: mounted update error
This commit is contained in:
parent
c6de34b5ef
commit
f5d51b3444
@ -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)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
|
17
packages/client/src/useMounted.ts
Normal file
17
packages/client/src/useMounted.ts
Normal 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
|
Loading…
Reference in New Issue
Block a user