const Post = (props) => {
const [isLoading, setLoading] = useState(true);
const [posts, setPosts] = useState([])
const [offset, setOffset] = useState(0)
const [hasPrev, setHasPrev] = useState(false)
const [hasNext, setHasNext] = useState(false)
const pageSize = 10
useEffect(() => {
const loadData = () => {
setLoading(true)
const requestOptions = getGraphqlRequestOptions(pageSize, offset)
fetch(graphql_url, requestOptions)
.then(response => {
setLoading(false)
return response.json()
})
.then(data => {
setHasNext(data.data.allPosts.pageInfo.hasNextPage)
setPosts(data.data.allPosts.edges)
setHasPrev(offset !== 0)
})
}
loadData()
}, [offset]);
const handleNextClick = () => {
setOffset(offset + pageSize)
};
const handlePrevClick = () => {
setOffset(offset - pageSize)
};
useEffect(()=> {
document.title = "MyTitle"
setOffset(0)
}, []);
return (
<>
... code to display table
<div className="row mb-5">
<Button
variant="outline-primary"
className="col-1 me-auto"
disabled={!(hasPrev || isLoading)}
size="sm" block
onClick={!isLoading ? handlePrevClick : null}
>
{isLoading ? 'Loading...' : 'Previous'}
</Button>
<Button
className="col-1 ms-auto"
disabled={!(hasNext || isLoading)}
onClick={!isLoading ? handleNextClick: null}
variant="outline-primary" size="sm" block
>
{isLoading ? 'Loading...' : 'Next'}
</Button>
</div>
</>
}
I was stuck because there were many options and no concrete example to implement this.
For example:
query{allPosts(first:10, after:"last cursor"){pageInfo{hasPrevPage hasNextPage startCursor endCursor} edge{node{...}}}
query{allPosts(first:10, offset:0){}} // currently used
last:10
instead of first:10, etc.hasNextPage, hasPrevPage, startCursor, endCursor
.
first
and after
option, hasPrevPage
was always false
before
option, hasNextPage
was always false