fix(slate-react): prevent useSelected from throwing when element is removed#6073
fix(slate-react): prevent useSelected from throwing when element is removed#6073NikunjSonigara wants to merge 2 commits into
Conversation
🦋 Changeset detectedLatest commit: 2840d76 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
There was a problem hiding this comment.
The general pattern we have been using to stop throwing is to make this opt-in. Some people prefer that things throw rather than failing silently. There are a few recent PRs that have made error throwing configurable, so I would prefer that approach. For example #6072.
Also there are a lot of comments in here that I would consider to be over-explaining by AI, please clean those up.
…Throw Address review feedback on ianstormtaylor#6073: instead of silently swallowing the error, add an opt-in `suppressThrow` option to `useSelected` so the hook keeps throwing by default and callers opt in to returning `false` when the element can no longer be resolved. Follows the `suppressThrow` pattern from ianstormtaylor#6072. Also trim the explanatory comments.
|
Thanks for the review @dylans, I have updated the PR:
Since the default still throws, users hitting #6053 opt in via |
Fixes
Fixes #6053
Summary
This PR prevents
useSelectedfrom throwing when the referenced element has been removed from the editor while still being referenced by a mounted React component.Previously, when an element was deleted,
ReactEditor.findPathorEditor.rangecould throw:This would cause runtime crashes in components still holding a reference to the removed element.
Solution
The path resolution and range calculation are now wrapped in a
try/catch. If the element can no longer be resolved (because it has been removed from the editor tree),useSelectedsafely returnsfalseinstead of throwing.Why this works
When the element is removed, it is no longer part of the editor's document tree, so selection state should be treated as
falserather than attempting to compute a range on a non-existent node.Test coverage
A regression test was added to ensure:
useSelected()returnsfalseafter the element is removedNotes
This fixes a real-world crash scenario where stale element references exist during React render cycles after DOM updates in Slate.