I need to update an array of data in Vue.js every time new data is received from Pusher. Reactivity is important to me, as I want to avoid reloading all the data from the server whenever an event is triggered.
Here's the specific condition I need to adhere to for updating my array:
/**
*
* 1. Ensure that each array chunk does not store more than 4 items
*
* 2. If all chunks already contain 4 items, create a new chunk,
* move the oldest item to the new chunk, and add the new data.
*
* ------------ Example ------------
*
* const beforeUnshift = [
* 0 => [7, 6, 5, 4],
* 1 => [3, 2, 1, 0]
* ];
*
* const afterUnshift = [
* 0 => [8, 7, 6, 5],
* 1 => [4, 3, 2, 1],
* 2 => [0]
* ];
*
* const afterSecondaryUnshift = [
* 0 => [9, 8, 7, 6],
* 1 => [5, 4, 3, 2],
* 2 => [1, 0]
* ];
*
* and so on...
*/
I have code in place that successfully updates the page with new data every time an event is fired. However, this process results in the entire page getting refreshed downwards until a manual refresh is performed.
<template>
<div class="table-swipable" style="overflow-x: hidden;">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="flightChunk in chunkedFlights">
<div class="table-responsive">
<table class="table">
<thead>
...
(Table structure HTML continued)
...
</tbody>
</table>
</div>
</div>
</div>
</div>
</template>
<script>
import Swiper from "swiper";
import moment from "moment";
export default {
data() {
return {
flights: {}
};
},
computed: {
chunkedFlights() {
return _.chunk(this.flights.data, 4);
}
},
created() {
Echo.channel("flight-created").listen("FlightCreated", ({ flights }) => {
this.chunkedFlights[0].unshift(flights[0]);
this.$forceUpdate();
});
},
filters: {
removeSecond(time) {
if (!time) return "";
return moment(time).format("hh:mm");
}
},
updated() {
var tableSwipable = new Swiper(".table-swipable", {
centeredSlides: true,
slidesPerView: 1,
spaceBetween: 60,
autoplay: {
delay: 30000
}
});
},
mounted() {
axios.get("/flights/public").then(response => {
this.flights = response.data;
});
}
};
</script>