Skip to content

Instantly share code, notes, and snippets.

@dohomi
Last active February 23, 2021 10:16
Show Gist options
  • Save dohomi/8de918fa638c548df29dd00254a4a274 to your computer and use it in GitHub Desktop.
Save dohomi/8de918fa638c548df29dd00254a4a274 to your computer and use it in GitHub Desktop.
combine Nuxt asyncData with vue-apollo and watchQuery for client search
<script>
import allTravelsGql from '../../GQL/travel/allTravels.gql'
import {pagination, getSkipFirst} from '../../../generated-cms/util/pagination'
import {getTravelQuery, setCategoryOnQuery} from '../../util/getTravelQuery'
const buildQuery = variables => {
return {
query: allTravelsGql,
variables,
manual: true,
update: r => r
}
}
const buildVariables = (pagination, query, store) => {
const {skip, first} = getSkipFirst(pagination)
const categories = setCategoryOnQuery(query)
const filter = getTravelQuery(categories, store.state.locale, query.q)
return {skip, first, filter}
}
export default {
layout: 'travelLayout',
middleware: ['setPageTemplates'],
components: {
MainFooter,
TravelListItem,
TravelsSearchBar,
MainSearch,
MainSidebar,
PageToolbar,
TravelList
},
data () {
return {
categories: {},
pagination: Object.assign({}, pagination),
travels: [],
count: 0
}
},
async asyncData ({app, store, query}) {
const variables = buildVariables(pagination, query, store)
const {data} = await app.apolloProvider.defaultClient.query(buildQuery(variables))
return {
travels: data.allTravels,
count: data._allTravelsMeta.count
}
},
methods: {
loadMore () {
this.pagination.page += 1
const {skip, first} = getSkipFirst(this.pagination)
this.fetchMoreGql('travelsGql', {first, skip})
},
updateQuery () {
this.addSmartQuery()
const {skip, first} = getSkipFirst(pagination)
const filter = getTravelQuery(this.categories, this.$store.state.locale, this.$store.state.mainSearch)
const variables = {skip, first, filter}
this.$apollo.queries.travelsGql.refetch(variables)
},
addSmartQuery () {
const variables = buildVariables(pagination, this.$route.query, this.$store)
if (this.$apollo.queries.travelsGql) return
this.$apollo.addSmartQuery('travelsGql', Object.assign({}, buildQuery(variables), {
result ({data, stale, loading}) {
if (loading === false && stale === false) {
const count = data._allTravelsMeta.count
const travels = data.allTravels
this.count = count
this.travels = travels
}
}
}))
}
},
watch: {
'$store.state.mainSearch' () {
this.updateQuery()
},
'categories': {
handler () {
this.updateQuery()
},
deep: true
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment