/* Select Input Common React Component Inspired By: react-select , https://codepen.io/dixie0704/pen/jOVxGXL, and others Created By: Aji Kamaludin */ import React, { useRef, useEffect, useState } from 'react' import { useDebounce } from '@/Hooks' export default function CategorySelectInput(props) { const { value = '', onItemSelected = null, disabled = false, createNew = null, invalid = false} = props const ref = useRef() const [showItems, setShowItem] = useState([]) const [isSelected, setIsSelected] = useState(true) const [selected, setSelected] = useState(value) const [query, setQuery] = useState('') const q = useDebounce(query, 300) const [isOpen, setIsOpen] = useState(false) const [loading, setLoading] = useState(false) const toggle = () => { setIsSelected(false) setQuery('') setIsOpen(!isOpen) } const onInputMouseDown = () => { setIsSelected(false) setQuery('') setIsOpen(true) } const handleSelectItem = (item) => { setIsSelected(true) onItemSelected(item) setSelected(item.name) setIsOpen(false) } const filterItems = (value) => { setIsSelected(false) setQuery(value) } useEffect(() => { const checkIfClickedOutside = (e) => { if (isOpen && ref.current && !ref.current.contains(e.target)) { setIsOpen(false) } } document.addEventListener('mousedown', checkIfClickedOutside) return () => { document.removeEventListener('mousedown', checkIfClickedOutside) } }, [isOpen]) useEffect(() => { setLoading(true) fetch(`${route('api.categories.query')}?q=${q}`) .then((res) => res.json()) .then((json) => { setShowItem(json) }) .catch((err) => { alert(err) }) .finally(() => setLoading(false)) }, [q]) useEffect(() => { setSelected('') }, [disabled]) useEffect(() => { setSelected(value) }, [value]) return (
filterItems(e.target.value)} disabled={disabled} />
{} : toggle}>
{isOpen && (
{loading ? (
Loading...
) : ( <> {createNew !== null && (
New
)} {showItems.map((item, index) => (
handleSelectItem(item) } >
{item.name}
))} {showItems.length <= 0 && (
No Items Found
)} )}
)}
) }