On dropdown click call API with first 10 item and display in the dropdown list. after then if user scroll down of the dropdown list then again call api with other 10 item. also same thing filter if user search any things then start from 1 page. in sort i need to implement infinite scroll of primereact multiselect
import React, { useState, useEffect, useRef } from "react";
import { MultiSelect } from "primereact/multiselect";
import { VirtualScroller } from "primereact/virtualscroller"; // Import VirtualScroller
export default function FilterDemo() {
const [selectedCities, setSelectedCities] = useState([]);
const [cities, setCities] = useState([]);
const [loading, setLoading] = useState(false);
const [pageNumber, setPageNumber] = useState(1);
const pageSize = 10;
const endReachedThreshold = 200; // Adjust this value based on your UI
const containerRef = useRef(null);
useEffect(() => {
const fetchCities = async () => {
setLoading(true);
try {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?_page=${pageSize}&_limit=10`
);
const data = await response.json();
setCities((prevCities) => [...prevCities, ...data]); // Append fetched data to cities
} catch (error) {
console.error("Error fetching cities:", error);
}
setLoading(false);
};
fetchCities();
}, [pageNumber]); // Fetch cities when page number changes
const handleScroll = () => {
const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
if (scrollHeight - scrollTop <= clientHeight + endReachedThreshold) {
setPageNumber((prevPageNumber) => prevPageNumber + 1);
}
};
return (
<MultiSelect
value={selectedCities}
onChange={(e) => setSelectedCities(e.value)}
options={cities}
optionLabel="name"
filter
onScroll={handleScroll}
placeholder="Select Cities"
maxSelectedLabels={3}
className="w-full md:w-20rem"
></MultiSelect>
);
}