import { useEffect } from "react"; import ItemList from "../components/ItemList"; import { useState } from 'react'; import Sorting from "../components/Sorting" import Filters from '../components/Filters'; import { useLocation } from 'react-router-dom'; import ResearchBar from "../components/ResearchBar"; const Morceaux = () => { const [products, setProducts] = useState([]); const [isLoading, setIsLoading] = useState(true); const [order, setOrder] = useState(""); const [filterPrice, setFilterPrice] = useState(""); const [filterState, setFilterState] = useState(""); const [isSearch, setIsSearch] = useState(false); const [query, setQuery] = useState(""); const { state } = useLocation(); useEffect(() => { document.title = 'Morceaux'; setIsLoading(true); setIsSearch(false); async function fetchData(isSearch) { var url = ""; url = isSearch ? `https://localhost:7292/api/Search?query=${state.query}` : `https://localhost:7292/api/Inventory`; const response = await fetch(url); const json = await response.json(); setProducts([...json]); } if (state != null) { setQuery(state.query); setIsSearch(true); fetchData(true); } else { fetchData(false); } setIsLoading(false); }, [state]); const handleNextItems = async () => { var url; if (products.length > 0) url = `https://localhost:7292/api/Inventory?lastId=${products[products.length - 1].id}&order=${order}&filterPrice=${filterPrice}&filterState=${filterState}`; else url = `https://localhost:7292/api/Inventory?order=${order}&filterPrice=${filterPrice}&filterState=${filterState}` setIsLoading(true); const response = await fetch(url); const json = await response.json(); //TODO: regler bug qui permet d'avoir des duplicats (trouver une façon de skipper les duplicats) if (json.length > 0) setProducts([...products, ...json]); setIsLoading(false); } const handleOrder = async (sortBy) => { setIsLoading(true); setOrder(sortBy); var url = isSearch ? `https://localhost:7292/api/Search?query=${query}&filterPrice=${filterPrice}&filterState=${filterState}&order=${sortBy}` : `https://localhost:7292/api/Inventory?order=${sortBy}&filterPrice=${filterPrice}&filterState=${filterState}`; const response = await fetch(url); const json = await response.json(); setProducts([...json]); setIsLoading(false); } const handleFilters = async (price, state) => { setIsLoading(true); setFilterPrice(price); setFilterState(state); var url = isSearch ? `https://localhost:7292/api/Search?query=${query}&filterPrice=${price}&filterState=${state}&order=${order}` : `https://localhost:7292/api/Inventory?order=${order}&filterPrice=${price}&filterState=${state}`; const response = await fetch(url); const json = await response.json(); setProducts([...json]); setIsLoading(false); } const handleScroll = async (e) => { const target = e.target; if (!isLoading && !isSearch) { if (target.scrollTop + target.clientHeight + 300 >= target.scrollHeight) { await handleNextItems(); } } } return (