I want to implement something like infinity scrolling on my application. This is my code:
import React, { useState, useEffect } from "react";
import AsyncSelect from "react-select/async";
const WithPromises = () => {
const [page, setPage] = useState(1);
const [allData, setAllData] = useState([]); //here should be added all data
const [scrolll, setScrolll] = useState();
const filterData = (inputValue) => {
const req = fetch(
`https://jsonplaceholder.typicode.com/todos?_limit=15&_page=${page}`
)
.then((response) => response.json())
.then((res) => {
const fetchedData = res.map(({ title }) => {
return {
label: title,
value: title
};
});
page > 1 && setAllData([...allData, ...fetchedData]);
return [...fetchedData, allData];
});
return req;
};
const promiseOptions = (inputValue) => {
return filterData(inputValue);
};
const scroll = (e) => {
console.log(e);
setScrolll(e);
promiseOptions();
};
useEffect(() => {
setPage(page + 1);
}, [scrolll, page]);
return (
<AsyncSelect
cacheOptions
onMenuScrollToBottom={scroll}
isClearable={true}
isSearchable={true}
defaultOptions
loadOptions={promiseOptions}
/>
);
};
export default WithPromises;
How you can see, i increment the page when the scroll section is at the bottom: setPage(page + 1);. This value is added in the api https://jsonplaceholder.typicode.com/todos?_limit=15&_page=${page}.
Also i want to concat all data from each scroll here: return [...fetchedData, allData]. At the end i need to achieve something like this:
User scrolls down and in the scroll section are added mew values, but previous should't dissapear, so on every scrolling when the scroll bar is at the bottom the new data should be added at the bottom of the select.
Issue: I can't achieve what i described above and i don't know the issue.
Question: How to solve the issue in my situation?
demo: https://codesandbox.io/s/codesandboxer-example-forked-zsj6i?file=/example.js:0-1262