From 227f7905b0549902d93c6aa817784f366ce1823e Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Tue, 8 Oct 2019 09:49:23 -0600 Subject: [PATCH] Upgrade controlled pagination example for deduped fetching --- examples/pagination-controlled/src/App.js | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/examples/pagination-controlled/src/App.js b/examples/pagination-controlled/src/App.js index eaf5a5b..d6ae812 100644 --- a/examples/pagination-controlled/src/App.js +++ b/examples/pagination-controlled/src/App.js @@ -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); }, []);