Heeeeey guys!
My name is Gustavo Scarpim, and I will show you how to consume a GitHub API in Vue.
I will show only the API part and leave the complete code at the end of this post.
1- Create your template:
<template>
<div>
<div class="card" v-if="loading === false">
<avatar circle size="sm" :img="userData.avatar_url"/>
<user :perfil="perfilUsuario"/>
<div class="repositorios">
<ul id="myList" v-if="userRepositories.length > 0">
<h4>Repositórios</h4>
<small>Total: {{userRepositories.length}}</small>
<hr>
<li v-for="repository in userRepositories" :key="repository.id">{{repository.name}}</li>
</ul>
</div>
</div>
<div v-if="loading" style="margin-top: 40px; align-items: center; justify-content: center;">
<cube-spin v-if="loading"/>
</div>
</div>
</template>
We will create 2 methods:
getUser to get user data:
getUser(name) {
this.loading = true
fetch(`https://api.github.com/users/${name}`, {
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
method: "GET"
})
.then(response => {
response.json().then(x => (this.userData = x))
this.loading = false
})
.catch(error => {
console.log(error)
this.loading = false
});
},
getRepos to get user repositories data:
getRepos(name) {
fetch(`https://api.github.com/users/${name}/repos`, {
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
method: "GET"
})
.then(response => response.json().then(x => (this.userRepositories = x)))
.catch(error => console.log(error));
},
2- Create your script
<script>
import Avatar from "./Avatar";
import User from "./User";
import CubeSpin from 'vue-loading-spinner/src/components/RotateSquare2'
export default {
components: { Avatar, User, CubeSpin },
name: "",
props: {
userName: String
},
data: () => ({
userData: "",
userRepositories: [],
loading: false,
}),
computed: {
perfilUsuario () {
return {
name: this.userData.name,
bio: this.userData.bio,
location: this.userData.location,
blog: this.userData.blog
};
}
},
methods: {
getUser(name) {
this.loading = true
fetch(`https://api.github.com/users/${name}`, {
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
method: "GET"
})
.then(response => {
response.json().then(x => (this.userData = x))
this.loading = false
})
.catch(error => {
console.log(error)
this.loading = false
});
},
getRepos(name) {
fetch(`https://api.github.com/users/${name}/repos`, {
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
method: "GET"
})
.then(response => response.json().then(x => (this.userRepositories = x)))
.catch(error => console.log(error));
},
},
watch: {
userName(context) {
this.getUser(context);
this.getRepos(context);
}
}
};
</script>
And ready!
The call to your api is already finished, if you want to see the code in action, just click on the link below, the same for the source code.
See the complete code here on GitHub Click Here
Check out the Project in action Deploy
Thanks for reading.
Top comments (0)