From f5d51b3444a0c205b4bf08fb3609758c18f34831 Mon Sep 17 00:00:00 2001 From: Eric Maciel Date: Tue, 27 Oct 2020 18:29:23 -0400 Subject: [PATCH] fix: mounted update error --- packages/client/src/useCursor.ts | 10 ++++++++-- packages/client/src/useMounted.ts | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 packages/client/src/useMounted.ts diff --git a/packages/client/src/useCursor.ts b/packages/client/src/useCursor.ts index ed89253..0fb4e8b 100644 --- a/packages/client/src/useCursor.ts +++ b/packages/client/src/useCursor.ts @@ -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([]) + const [cursorData, setCursorData] = useState([]) + 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) + } } }, []) diff --git a/packages/client/src/useMounted.ts b/packages/client/src/useMounted.ts new file mode 100644 index 0000000..6c51b94 --- /dev/null +++ b/packages/client/src/useMounted.ts @@ -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