51 lines
1.3 KiB
JavaScript
51 lines
1.3 KiB
JavaScript
import React, { useState, useContext } from 'react'
|
|
import { AuthContext } from '../context/AuthContext'
|
|
import api from '../api'
|
|
import '../styles/global.css'
|
|
|
|
export default function SearchBar() {
|
|
const [query, setQuery] = useState('')
|
|
const [results, setResults] = useState([])
|
|
const [showResults, setShowResults] = useState(false)
|
|
|
|
const handleSearch = async (e) => {
|
|
const value = e.target.value
|
|
setQuery(value)
|
|
|
|
if (value.length > 2) {
|
|
try {
|
|
const response = await api.get('/products/search', {
|
|
params: { q: value },
|
|
})
|
|
setResults(response.data)
|
|
setShowResults(true)
|
|
} catch (error) {
|
|
console.error('Search error:', error)
|
|
}
|
|
} else {
|
|
setShowResults(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="search-bar">
|
|
<input
|
|
type="text"
|
|
placeholder="Search products..."
|
|
value={query}
|
|
onChange={handleSearch}
|
|
/>
|
|
{showResults && results.length > 0 && (
|
|
<div className="search-results">
|
|
{results.map((product) => (
|
|
<a key={product.id} href={`/product/${product.id}`} className="search-result-item">
|
|
<span>{product.name}</span>
|
|
<span>₪{product.price.toFixed(2)}</span>
|
|
</a>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|