Skip to content

Commit

Permalink
Upgrade controlled pagination example for deduped fetching
Browse files Browse the repository at this point in the history
  • Loading branch information
tannerlinsley committed Oct 8, 2019
1 parent f1ad032 commit 227f790
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions examples/pagination-controlled/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}, []);

Expand Down

0 comments on commit 227f790

Please sign in to comment.