How can I update my VueJs Data function properties value while fetching data from API using axios? - laravel

I have successfully fetched data from API. The fetched data shows in the alert function. However, the properties in the data function such as - 'Recovered' is not updating. I can show the fetched data using Vanilla JS. But I want to update them automatically and want to show them like this {{Recovered}}.
How can I do it??
<template>
<div class="container">
<h2>Total Recovered: {{Recovered}}</h2>
</div>
</template>
<script>
import axios from 'axios'
export default {
name:'CoronaStatus',
data: function () {
return {
Recovered: '',
TotalConfirmed: '',
TotalDeaths: '',
// test: '30',
// test_2: 'maheeb',
// componentKey: 0,
}
},
mounted(){
this.globalStatus();
},
methods:{
globalStatus: function(){
// const self = this;
// this.componentKey += 1;
axios.get('https://api.covid19api.com/summary')
.then((response) => {
// this.recovered = response.data.Global.NewConfirmed;
this.Recovered= response.data.Global.TotalRecovered;
alert(this.Recovered);
// document.getElementById('test_5').innerHTML = "total: " + this.TotalRecovered;
}).catch(err=> console.log(err));
},
}
}
</script>
<style scoped>
</style>

The easiest solution would be to refetch the information every hour with setInterval.
The best solution would be to use the WebHook provided by covid19api.com.
Vue.config.devtools = false;
Vue.config.productionTip = false;
var app = new Vue({
el: '#app',
data: {
Recovered: "Loading ..."
},
mounted() {
setInterval(() => {
this.globalStatus();
}, 3600000); // Call globalStatus every hour
this.globalStatus();
},
methods: {
globalStatus: function() {
axios
.get("https://api.covid19api.com/summary")
.then(response => {
this.Recovered = response.data.Global.TotalRecovered;
})
.catch(err => console.log(err));
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<div id="app">
<h2>Total Recovered: {{ Recovered }}</h2>
</div>

Related

Show component only after all images loaded

I am using Vue 3 and what i would like to achieve is to load all images inside a card (Album Card) and only then show the component on screen..
below is an how it looks now and also my code.
Does anybody have an idea how to achieve this?
currently component is shown first and then the images are loaded, which does not seem like a perfect user experience.
example
<template>
<div class="content-container">
<div v-if="isLoading" style="width: 100%">LOADING</div>
<album-card
v-for="album in this.albums"
:key="album.id"
:albumTitle="album.title"
:albumId="album.id"
:albumPhotos="album.thumbnailPhotos.map((photo) => photo)"
></album-card>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import albumCard from "#/components/AlbumCard.vue";
interface Album {
userId: number;
id: number;
title: string;
thumbnailPhotos: Array<Photo>;
}
interface Photo {
albumId: number;
id: number;
title: string;
url: string;
thumbnailUrl: string;
}
export default defineComponent({
name: "Albums",
components: {
albumCard,
},
data() {
return {
albums: [] as Album[],
isLoading: false as Boolean,
};
},
methods: {
async getAlbums() {
this.isLoading = true;
let id_param = this.$route.params.id;
fetch(
`https://jsonplaceholder.typicode.com/albums/${
id_param === undefined ? "" : "?userId=" + id_param
}`
)
.then((response) => response.json())
.then((response: Album[]) => {
//api returns array, loop needed
response.forEach((album: Album) => {
this.getRandomPhotos(album.id).then((response: Photo[]) => {
album.thumbnailPhotos = response;
this.albums.push(album);
});
});
})
.then(() => {
this.isLoading = false;
});
},
getRandomPhotos(albumId: number): Promise<Photo[]> {
var promise = fetch(
`https://jsonplaceholder.typicode.com/photos?albumId=${albumId}`
)
.then((response) => response.json())
.then((response: Photo[]) => {
const shuffled = this.shuffleArray(response);
return shuffled.splice(0, 3);
});
return promise;
},
/*
Durstenfeld shuffle by stackoverflow answer:
https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array/12646864#12646864
*/
shuffleArray(array: Photo[]): Photo[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
},
},
created: function () {
this.getAlbums();
},
});
</script>
What i did to solve this problem was using function on load event on (img) html tag inside album-card component. While images are loading a loading spinner is shown. After three images are loaded show the component on screen.
<template>
<router-link
class="router-link"
#click="selectAlbum(albumsId)"
:to="{ name: 'Photos', params: { albumId: albumsId } }"
>
<div class="album-card-container" v-show="this.numLoaded == 3">
<div class="photos-container">
<img
v-for="photo in this.thumbnailPhotos()"
:key="photo.id"
:src="photo.thumbnailUrl"
#load="loaded()"
/>
</div>
<span>
{{ albumTitle }}
</span>
</div>
<div v-if="this.numLoaded != 3" class="album-card-container">
<the-loader></the-loader>
</div>
</router-link>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { store } from "#/store";
export default defineComponent({
name: "album-card",
props: {
albumTitle: String,
albumsId: Number,
},
data: function () {
return {
store: store,
numLoaded: 0,
};
},
methods: {
thumbnailPhotos() {
return this.$attrs.albumPhotos;
},
selectAlbum(value: string) {
this.store.selectedAlbum = value;
},
loaded() {
this.numLoaded = this.numLoaded + 1;
},
},
});
</script>
Important note on using this approach is to use v-show instead of v-if on the div. v-show puts element in html(and sets display:none), while the v-if does not render element in html so images are never loaded.

in vue.js i am trying to get row count but it returning null

im trying to get row cout but returning 0 only.
my code
<template>
<div>
<p>{{ resultCount }}</p>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
registerlist: [],
};
},
async asyncData({ $axios }) {
let { data } = await $axios.$get("/Businessregisterlist");
// console.log(response)
return {
registerlist: data,
};
},
computed: {
resultCount() {
return Object.keys(this.registerlist).length;
},
},
};
</script>
This is because when you return a property in asyncData, you should not have it in data property of the component instance, instead the later will override the returned with asyncData.
<script>
import axios from "axios";
export default {
async asyncData({ $axios }) {
let { data } = await $axios.$get("/Businessregisterlist");
// console.log(response)
return {
registerlist: data,
};
},
computed: {
resultCount() {
return Object.keys(this.registerlist).length;
},
},
};
</script>
<template>
<div>
<p>{{ resultCount }}</p>
</div>
</template>

How to instant data refresh with Laravel and vue.js?

I work with constantly changing api data. I use Laravel and Vue.js. There is a steady stream of data when I control the network with F11. But it has no effect on the DOM.
Here are sample codes. I would be glad if you help.
HTML code;
<div class="row">
<div class="col-md-12">
<p class="tv-value" v-html="totalMeetings"></p>
</div>
</div>
Script Code;
<script>
export default {
data() {
return {
totalMeetings: null
}
},
created() {
this.getPosts();
},
methods: {
getPosts() {
axios
.get("/get-total-meetings")
.then(response => (this.totalMeetings = response.data))
.catch(error => {
this.errors.push(error);
});
}
},
mounted() {
setInterval(function () {
axios
.get("/get-total-meetings")
.then(response => (this.totalMeetings = response.data))
.catch(error => {
this.errors.push(error);
});
}, 2000)
}
}
</script>
Change your setInterval function to arrow function like this.
setInterval(() => {
axios
.get("/get-total-meetings")
.then(response => (this.totalMeetings = response.data))
.catch(error => {
this.errors.push(error);
});
}, 2000);
You could put a watcher for that to be able vue to watch the changes of your data. like this.
watch: {
totalMeetings(val) {
this.totalMeetings = val
}
}
Or create a computed property for it to update the value when it changes.
computed: {
total_meetings() {
return this.totalMeetings
}
}
then your component should look like this
<p class="tv-value" v-html="total_meetings"></p>

vue component doesn't show data

Axios loads data without any problem, doesn't show any data, Laravel Mix builds without error.
I have following code:
index.html (body)
<div id="app">
<posts></posts>
</div>
In app.js I use this:
import Vue from 'vue';
// global declare axios
window.axios = require('axios');
import Posts from './components/Posts';
Vue.component('posts', Posts);
new Vue({
el: '#app',
props: {
posts:[{
userId: [Number],
id: [Number],
title: [String, Number]
}]
}
});
In the Posts.vue component I create a template and a script loading the data when mounted:
<template>
<ul>
<li v-for="post in posts" v-text="post.title"></li>
</ul>
</template>
<script>
export default {
data: function() {
return {
posts: null,
}
},
// when stuff is loaded (document ready)
mounted: function() {
// use placeholder data for tests, capture asynchronous data from site using this.
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => this.posts = response.posts)
.catch(error => this.posts = [{title: 'No posts found.'}])
.finally(console.log('Posts loading complete'));
},
}
</script>
So the data should be shown as a ul list:
<ul>
<li>
title
</li>
<li>
title
</li>
<li>
title
</li>
</ul>
Try the code below, I've made comments on the bits that need changing.
data() {
return {
posts: [] // this should be an array not null
};
},
// you can do this on created instead of mounted
created() {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
this.posts = response.data; // add data to the response
});
` Here "this.post" not take it has instance in axios call.So you have follow like this. `
var vm=this;
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => vm.posts = response.posts)
.catch(error => vm.posts = [{title: 'No posts found.'}])
.finally(console.log('Posts loading complete'));

Table Updates and AJAX Calls

I'm fairly new to Vue so I'm not sure whether being stupid or not.
I have a table that needs to be updated at a regular interval, so far I've used AJAX to make a call to an API and return the data and that all works great. I'm able to display all my data as required, the issue I'm facing, and this is where my knowledge gets fuzzy, is that on each AJAX call my entire table appears to be getting re-rendered, I thought, or rather hoped, that Vue would only "replace" the data that has changed not the whole table.
Is such a thing possible or am I asking too much?
I've included my code below incase I'm doing something wrong.
App.vue
<template lang="pug">
.user-agent-overview
.container
av-table(:columns="columns" :agentData="agentData")
</template>
<script>
import axios from 'axios';
import avTable from './Table';
export default {
data() {
return {
agentData: null,
columns: [
'Agent Name',
'Status',
'First Log in',
'Last Log out',
'Total On duty',
'Total Inbound',
'Total Outbound',
'Average Talk time',
'Total Talk time',
],
};
},
created() {
this.fetchAgentData();
},
methods: {
fetchAgentData() {
this.error = null;
this.agentData = null;
this.loading = true;
axios
.get('/api/v1/ajax-dashboard-aircall/agents')
.then(response => {
this.agentData = response.data.user_agents;
})
.catch(error => {
});
},
},
components: {
avTable,
},
mounted() {
// this.$nextTick(() => {
// setInterval(function() {
// this.fetchAgentData();
// }.bind(this), 5000);
// });
},
};
</script>
Table.vue
<template lang="pug">
table.table
thead
tr
th(v-for="column in columns") {{ column }}
tbody
tr(v-for="(data, dIndex) in agentData" :key="dIndex")
td(v-for="(item, iIndex) in data" :key="`${iIndex}-${iIndex}`") {{ item }}
</template>
<script>
import axios from 'axios';
export default {
props: ['columns', 'agentData'],
};
</script>
Thanks David

Resources