From 7403a47f4230bbde600d64eb678cef5c3ee14c2b Mon Sep 17 00:00:00 2001 From: Ian Sanders Date: Thu, 26 Jan 2023 14:57:01 -0500 Subject: [PATCH] Improve initial `useCombobox` initialization process (#2818) * Improve initial combobox initialization process * Create .changeset/olive-glasses-listen.md --- .changeset/olive-glasses-listen.md | 5 +++++ src/drafts/hooks/useCombobox.ts | 5 +++-- 2 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 .changeset/olive-glasses-listen.md diff --git a/.changeset/olive-glasses-listen.md b/.changeset/olive-glasses-listen.md new file mode 100644 index 00000000000..5ae87f99651 --- /dev/null +++ b/.changeset/olive-glasses-listen.md @@ -0,0 +1,5 @@ +--- +"@primer/react": patch +--- + +Improve initial `useCombobox` initialization process to avoid race conditions diff --git a/src/drafts/hooks/useCombobox.ts b/src/drafts/hooks/useCombobox.ts index bc7ae732348..c821f069cf5 100644 --- a/src/drafts/hooks/useCombobox.ts +++ b/src/drafts/hooks/useCombobox.ts @@ -97,7 +97,6 @@ export const useCombobox = ({ if (!list.getAttribute('role')) list.setAttribute('role', 'listbox') const cb = new Combobox(input, list, {tabInsertsSuggestions, defaultFirstOption}) - if (isOpenRef.current) cb.start() // By using state instead of a ref here, we trigger the toggleKeyboardEventHandling // effect. Otherwise we'd have to depend on isOpen in this effect to start the instance @@ -116,7 +115,9 @@ export const useCombobox = ({ useEffect( function toggleKeyboardEventHandling() { const wasOpen = isOpenRef.current - isOpenRef.current = isOpen + + // It cannot be open if the instance hasn't yet been initialized + isOpenRef.current = isOpen && comboboxInstance !== null if (isOpen === wasOpen || !comboboxInstance) return