Skip to content

useSelected error when remove myself #6053

Description

@BataevDaniil

I get an error in useSelected() when I try to delete myself.

const Options = React.forwardRef<any, { element: Element }>((props, ref) => {
  const selected = useSelected()
  const editor = useSlateStatic()
  React.useEffect(() => {
    if (!selected) {
      try {
        const path = ReactEditor.findPath(editor, props.element)
        deleteOptionsWhenEmpty(editor, path)
      } catch (error) {
        Sentry.captureException(error)
      }
    }
  }, [selected])
  return <OptionsStyled selected={selected} {...props} ref={ref} />
})

I got error Error: Cannot find a descendant at path [0,1] in node

My local solution is copy pase useSlected and wrap const range = Editor.range(editor, path) in try catch

I proposle add it to lib

export const useSelectedMy = (): boolean => {
  const element = useElementIf()

  // Breaking the rules of hooks is fine here since `!element` will remain true
  // or false for the entire lifetime of the component this hook is called from.
  // TODO: Decide if we want to throw an error instead when calling
  // `useSelected` outside of an element (potentially a breaking change).
  if (!element) return false

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const selector = React.useCallback(
    (editor: Editor) => {
      if (!editor.selection) return false
      try {
        const path = ReactEditor.findPath(editor, element)
        const range = Editor.range(editor, path)
        return !!Range.intersection(range, editor.selection)
      } catch (errro) {
        console.log(errro)
      }
    },

    [element],
  )

  return useSlateSelector(selector, undefined, { deferred: true })
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions