Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ function Todos() {
latestData,
error,
isFetching,
} = usePaginatedQuery(['todos', page], fetchProjects)
} = usePaginatedQuery(['projects', page], fetchProjects)

return (
<div>
Expand Down
47 changes: 21 additions & 26 deletions examples/pagination/pages/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import React from 'react'
import fetch from '../libs/fetch'

import { usePaginatedQuery } from 'react-query'

export default () => {
function Todos() {
const [page, setPage] = React.useState(0)

const { status, resolvedData, data, error, isFetching } = usePaginatedQuery(
['projects', page],
(key, page = 0) => fetch('/api/projects?page=' + page)
)
const fetchProjects = (key, page = 0) => fetch('/api/projects?page=' + page)

const {
status,
resolvedData,
latestData,
error,
isFetching,
} = usePaginatedQuery(['projects', page], fetchProjects)

return (
<div>
Expand All @@ -18,37 +18,32 @@ export default () => {
) : status === 'error' ? (
<div>Error: {error.message}</div>
) : (
// The data from the last successful page will remain
// available while loading other pages
// `resolvedData` will either resolve to the latest page's data
// or if fetching a new page, the last successful page's data
<div>
{resolvedData.projects.map(project => (
<p
style={{
border: '1px solid gray',
borderRadius: '5px',
padding: '.5rem',
}}
key={project.id}
>
{project.name}
</p>
<p key={project.id}>{project.name}</p>
))}
</div>
)}
<span>Current Page: {page + 1}</span>{' '}
<span>Current Page: {page + 1}</span>
<button
onClick={() => setPage(old => Math.max(old - 1, 0))}
disabled={page === 0}
>
Previous Page
</button>{' '}
<button
onClick={() => setPage(old => old + 1)}
disabled={!data || !data.hasMore}
onClick={() =>
// Here, we use `latestData` so the Next Page
// button isn't relying on potentially old data
setPage(old => (!latestData || !latestData.hasMore ? old : old + 1))
}
disabled={!latestData || !latestData.hasMore}
>
Next Page
</button>
{// Since the data stick around between page requests,
{// Since the last page's data potentially sticks around between page requests,
// we can use `isFetching` to show a background loading
// indicator since our `status === 'loading'` state won't be triggered
isFetching ? <span> Loading...</span> : null}{' '}
Expand Down