I have a component that loads all products on component load. The component also has a search functionality that takes user input and querys database for products based on user input. Search results should replace any products that were initially loaded by the component. Below is the load and search functionality.
The problem I am seeing is that the search function does not replace the loaded products, but it appends any products returned by the search to the already load product list.
const [products, setProducts] = useState([]);
const [page, setPage] = useState(1);
const [limit] = useState(100);
const [searchQuery, setSearchQuery] = useState('');
useEffect(() => {
const loadProducts = async () => {
console.log('Fetching products for page:', page);
try {
const data = await fetchProducts(page, limit);
console.log('Fetched products:', data);
setProducts(prevProducts => [...prevProducts, ...data.products]);
} catch (err) {
console.error('Error fetching products:', err);
}
};
loadProducts();
}, [page, limit]);
const handleSearch = async () => {
console.log('Searching for products with query:', searchQuery);
try {
const data = await searchProducts(searchQuery);
setProducts(data.products);
setPage(1);
} catch (err) {
console.error('Error searching for products:', err);
}
};