Reputation: 489
I'm trying to implement pagination on my site using a nuxt frontend and a laravel backend serving a graphql endpoint using lighthouse.
reading the docs about the pagination directive has me asking lots of questions about how this works.
Unlike the normal laravel pagination way which is calling paginate()
on a model which than returns an object with the following items
{
"total": 50,
"per_page": 15,
"current_page": 1,
"last_page": 4,
"first_page_url": "http://laravel.app?page=1",
"last_page_url": "http://laravel.app?page=4",
"next_page_url": "http://laravel.app?page=2",
"prev_page_url": null,
"path": "http://laravel.app",
"from": 1,
"to": 15,
"data":[
{
// Record...
},
{
// Record...
}
]
}
graphql (or at least lighthouse) does it a bit different, mostly the following needs to be done.
you define a query
type Query {
blogs: [Blog!]! @paginate @orderBy(column: "created_at", direction: DESC)
}
Querying it via the graphql-playground with the following params first : 5, page:1
gives me the following object
{
"data": {
"blogs": {
"paginatorInfo": {
"count": 5,
"currentPage": 1,
"firstItem": 1,
"hasMorePages": true,
"lastItem": 5,
"lastPage": 2,
"perPage": 5,
"total": 10
},
"data": [
// items
]
}
},
}
Seems simple enough but I'm not entirely sure how to make this work on the front-end
I made a pagination component
<template>
<div class='btn-group bg-white py-2 items-center justify-center'>
<button class='btn'>Previous</button>
<button class='btn'>1</button>
<button class='btn btn-active'>2</button>
<button class='btn'>3</button>
<button class='btn'>4</button>
<button class='btn'>Next</button>
</div>
</template>
<script>
export default {
name: 'Pagination'
}
</script>
<style scoped>
</style>
And that's really as far as I have gotten, I've been banging my head for a few hours now reading up on apollo and pagination, but the only examples I have seen so far have been of the infinite scroll variety instead of good 'oll offset based pagination.
Upvotes: 1
Views: 795
Reputation: 659
On your client side, you will have a Graphql Query, with some Variables. For example:
query Blogs($page: Int!, $first: Int!) {
blogs(page: $page, first: $first) {
id
# ...
}
}
So, with Apollo, you have to call it passing those variables, like:
data() {
return {
page: 1,
}
},
apollo: {
blogs: {
query: gql`...`,
variables() {
return {
first: 15, // it could be dynamic
page: this.page, // in your component, you will have to change this variable to fetch another page
}
}
}
}
Then, everytime you change the page
variable, Apollo will make another query to fetch other pages. Usually I use premade components for pagination, like v-pagination.
Upvotes: 1