From ddf35200ac72c63d783ddeb4028f7c3f43a071df Mon Sep 17 00:00:00 2001 From: Erik Arvidsson Date: Wed, 18 Dec 2024 09:27:57 +0100 Subject: [PATCH] fix(zbugs): Fix lint warning in combobox (#3413) ESlint was complaining about exhaustive dependencies Use useClickOutside hook to reduce code duplication. --- apps/zbugs/src/components/combobox.tsx | 46 ++++++++++++-------------- 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/apps/zbugs/src/components/combobox.tsx b/apps/zbugs/src/components/combobox.tsx index e3fcd073f..93d4795c0 100644 --- a/apps/zbugs/src/components/combobox.tsx +++ b/apps/zbugs/src/components/combobox.tsx @@ -3,11 +3,13 @@ import { type KeyboardEvent, memo, type RefObject, + useCallback, useEffect, useRef, useState, } from 'react'; import DropdownArrow from '../assets/icons/dropdown-arrow.svg?react'; +import {useClickOutside} from '../hooks/use-click-outside.js'; import {umami} from '../umami.js'; import styles from './combobox.module.css'; import {fuzzySearch} from './fuzzySearch.js'; @@ -49,18 +51,21 @@ function Combobox({ const selectedItem = items.find(option => option.value === value); - const setMenuOpen = (b: boolean) => { - if (b !== isOpen) { - // Only track if state changes - if (b) { - openTimeRef.current = Date.now(); - umami.track('Combobox opened'); // Track open action - } else { - umami.track('Combobox closed'); // Track close action + const setMenuOpen = useCallback( + (b: boolean) => { + if (b !== isOpen) { + // Only track if state changes + if (b) { + openTimeRef.current = Date.now(); + umami.track('Combobox opened'); // Track open action + } else { + umami.track('Combobox closed'); // Track close action + } + setIsOpen(b); } - setIsOpen(b); - } - }; + }, + [isOpen], + ); const toggleDropdown = () => { setMenuOpen(!isOpen); @@ -73,19 +78,12 @@ function Combobox({ } }, [isOpen]); - useEffect(() => { - const handleMouseDown = (event: MouseEvent) => { - if ( - !inputRef.current?.contains(event.target as Element) && - !listboxRef.current?.contains(event.target as Element) - ) { - setMenuOpen(false); - } - }; - - document.addEventListener('mousedown', handleMouseDown); - return () => document.removeEventListener('mousedown', handleMouseDown); - }, []); + useClickOutside( + [inputRef, listboxRef], + useCallback(() => { + setMenuOpen(false); + }, [setMenuOpen]), + ); const selectIndex = (index: number) => { setSelectedIndex(index);