import React, { useState, useEffect } from "react";
import AsyncSelect from "react-select/async";
const WithPromises = () => {
const [page, setPage] = useState(1);
const [items, onItemsChange] = useState([]);
useEffect(() => {
fetchData(page);
}, [page]);
const fetchData = async (pageIdx) => {
const res = await fetch(
`https://jsonplaceholder.typicode.com/todos?_limit=15&_page=${pageIdx}`
).then((r) => r.json());
const resItems = res.map(({ title }) => ({
label: title,
value: title
}));
onItemsChange([...items, ...resItems]);
};
const loadOptions = () => items;
// for search functionality use something like this:
// const loadOptions = async (inputStr) => {
// const searchRes = await fetch(`${yourUrl}?search=${inputStr}`).then(r => r.json());
// return searchRes;
// };
const handleBottomScroll = () => {
setPage((prevVal) => prevVal + 1);
};
return (
<AsyncSelect
cacheOptions
isClearable={true}
isSearchable={true}
defaultOptions={items}
onMenuScrollToBottom={handleBottomScroll}
loadOptions={loadOptions}
/>
);
};
export default WithPromises;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…