Upgrade controlled pagination example for deduped fetching

This commit is contained in:
Tanner Linsley 2019-10-08 09:49:23 -06:00
parent f1ad032587
commit 227f7905b0

View File

@ -240,26 +240,33 @@ function App() {
const [data, setData] = React.useState([]);
const [loading, setLoading] = React.useState(false);
const [pageCount, setPageCount] = React.useState(0);
const fetchIdRef = React.useRef(0);
const fetchData = React.useCallback(({ pageSize, pageIndex }) => {
// This will get called when the table needs new data
// You could fetch your data from literally anywhere,
// even a server. But for this example, we'll just fake it.
// Give this fetch an ID
const fetchID = ++fetchIdRef.current;
// Set the loading state
setLoading(true);
// We'll even set a delay to simulate a server here
setTimeout(() => {
const startRow = pageSize * pageIndex;
const endRow = startRow + pageSize;
setData(serverData.slice(startRow, endRow));
// Only update the data if this is the latest fetch
if (fetchID === fetchIdRef.current) {
const startRow = pageSize * pageIndex;
const endRow = startRow + pageSize;
setData(serverData.slice(startRow, endRow));
// Your server could send back total page count.
// For now we'll just fake it, too
setPageCount(Math.ceil(serverData.length / pageSize));
// Your server could send back total page count.
// For now we'll just fake it, too
setPageCount(Math.ceil(serverData.length / pageSize));
setLoading(false);
setLoading(false);
}
}, 1000);
}, []);