Medium
You're implementing an infinite scroll feature with data caching. What needs to be fixed?
1function InfiniteList({ fetchData }) {2 const [items, setItems] = useState([]);3 const [page, setPage] = useState(1);4 const [loading, setLoading] = useState(false);5 const [error, setError] = useState(null);6 const cache = useRef({});7 const observer = useRef();89 const lastItemRef = useCallback((node) => {10 if (loading) return;1112 if (observer.current) {13 observer.current.disconnect();14 }1516 observer.current = new IntersectionObserver(entries => {17 if (entries[0].isIntersecting) {18 setPage(prev => prev + 1);19 }20 });2122 if (node) {23 observer.current.observe(node);24 }25 }, [loading]);2627 useEffect(() => {28 const loadMore = async () => {29 setLoading(true);30 try {31 if (cache.current[page]) {32 setItems(prev => [...prev, ...cache.current[page]]);33 } else {34 const newItems = await fetchData(page);35 cache.current[page] = newItems;36 setItems(prev => [...prev, ...newItems]);37 }38 } catch (err) {39 setError(err);40 } finally {41 setLoading(false);42 }43 };4445 loadMore();46 }, [page]);4748 return (49 <div>50 {items.map((item, index) => (51 <div52 key={item.id}53 ref={index === items.length - 1 ? lastItemRef : null}54 >55 {item.content}56 </div>57 ))}58 {loading && <div>Loading...</div>}59 {error && <div>Error: {error.message}</div>}60 </div>61 );62}