Skip to content

Instantly share code, notes, and snippets.

@alexcarpenter
Created September 13, 2018 22:29
Show Gist options
  • Save alexcarpenter/aa0542b05f7177df45872868b3b5f8d3 to your computer and use it in GitHub Desktop.
Save alexcarpenter/aa0542b05f7177df45872868b3b5f8d3 to your computer and use it in GitHub Desktop.
<template>
<div>
<article v-for="(post, index) in postsResults" :key="index">
<h2 class="card-title">
<a :href="post.uri">{{ post.title }}</a>
</h2>
<time>{{ post.dateCreated }}</time>
</article>
<button @click="fetchPosts()" :class="{ 'is-loading' : loading }" v-show="hasNextPage">Load More</button>
</div>
</template>
<script>
import axios from "axios";
const apiToken =
"4vZNYyleuaw9oPaenEQTvIDFQF03IClsB2EI4aeYEjtKrP7TlXmrnQUDIMJHH9R_";
const apiUrl = "/api";
const queryBlogPosts = `
query queryBlogPosts($limit: Int, $offset: Int){
entriesConnection(limit: $limit, offset: $offset, section: [blog]) {
totalCount
pageInfo {
hasPreviousPage
hasNextPage
currentPage
totalPages
first
last
}
entries {
title
uri
dateCreated @date(as:"F j, Y")
}
}
}
`;
const configureApi = (url, token) => {
return {
baseURL: url,
headers: {
Authorization: `Bearer ${token}`,
"X-Requested-With": "XMLHttpRequest"
}
};
};
const executeQuery = (api, query, variables, callback) => {
api
.post("", {
query: query,
variables: variables
})
.then(result => {
if (callback) {
callback(result.data);
}
console.log(result.data);
})
.catch(error => {
console.log(error);
});
};
export default {
name: "LoadMore",
data() {
return {
loading: 0,
postsApi: axios.create(configureApi(apiUrl, apiToken)),
postsResults: [],
nextPosts: 0,
hasNextPage: 1
};
},
methods: {
fetchPosts() {
this.loading = 1;
const variables = {
limit: 3,
offset: this.nextPosts + 3
};
executeQuery(this.postsApi, queryBlogPosts, variables, data => {
this.postsResults = this.postsResults.concat(
data.data.entriesConnection.entries
);
this.nextPosts = this.nextPosts + 3;
this.loading = 0;
});
}
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment