Skip to content

Commit

Permalink
fix not update state when unmounted (#4819)
Browse files Browse the repository at this point in the history
* fix not update state when unmounted

* add changeset
  • Loading branch information
ugaya40 authored Feb 5, 2022
1 parent 4b97197 commit 8066150
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/hot-beers-poke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'slate-react': patch
---

Fix a possible update of react state after Slate component is unmounted
7 changes: 6 additions & 1 deletion packages/slate-react/src/components/slate.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useMemo, useState, useCallback, useEffect } from 'react'
import React, { useMemo, useState, useCallback, useEffect, useRef } from 'react'
import { Editor, Node, Element, Descendant } from 'slate'
import { ReactEditor } from '../plugin/react-editor'
import { FocusedContext } from '../hooks/use-focused'
Expand All @@ -19,6 +19,7 @@ export const Slate = (props: {
onChange: (value: Descendant[]) => void
}) => {
const { editor, children, onChange, value, ...rest } = props
const unmountRef = useRef(false)

const [context, setContext] = React.useState<[ReactEditor]>(() => {
if (!Node.isNodeList(value)) {
Expand Down Expand Up @@ -47,6 +48,7 @@ export const Slate = (props: {
useEffect(() => {
return () => {
EDITOR_TO_ON_CHANGE.set(editor, () => {})
unmountRef.current = true
}
}, [])

Expand All @@ -59,6 +61,9 @@ export const Slate = (props: {
useIsomorphicLayoutEffect(() => {
const fn = () => {
setTimeout(() => {
if (unmountRef.current) {
return
}
setIsFocused(ReactEditor.isFocused(editor))
}, 0)
}
Expand Down

0 comments on commit 8066150

Please sign in to comment.