What is the process of shifting an object to the initial chunk and transferring the oldest item to a new chunk using JavaScript?

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>

Answer №1

In this scenario, separating your data from the view layer is a smart move. It simplifies handling updates by having a central source of truth that you can update, rather than directly updating individual chunks.

Whenever there is an update, add it to this.flights.data instead of modifying a chunk. Then, trigger vue to recalculate your chunks. By doing this, you maintain your original data array as the primary source of truth and update the chunks based on it for your view every time.

Answer №2

It seems that frodo2975 pointed out the issue with shifting into a calculated value instead of your data. I overlooked that initially. The corrected code now functions as intended:

new Vue({
  el: '#app',
  data: {
    flights: [
      7, 6, 5, 4, 3, 2, 1, 0
    ]
  },
  computed: {
    chunkedFlights() {
      return _.chunk(this.flights, 4);
    }
  },
  mounted() {
    setTimeout(() => {
      this.flights.unshift(8);
    }, 2000);
  }
});
#app {
  display: grid;
  grid-gap: 2rem;
  background-color: black;
  padding: 0.6rem;
}

.page {
  background-color: #ffe;
  padding: 0.6rem;
  grid-gap: 0.2rem;
  display: grid;
}

.row {
  background-color: blue;
  color: white;
  padding: 0.6rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="chunk in chunkedFlights" class="page">
    <div v-for="flight in chunk" class="row">
      {{flight}}
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing jQuery, a captivating slideshow showcasing a series of images elegantly emerges from the center-right of

I've been working on creating a slideshow of images and I came across this tutorial: After downloading the zip file and getting started, everything was working fine. The only issue I encountered was trying to position those four dots at the bottom ri ...

Issue with ReactJS: onChange event does not function properly when value is changed using jQuery

This is the reactjs code I am working with: <input name="date" id="date" value={this.state.listManage.date} onChange={this.handleForm} type="text" /> When I manually type in the input field, the onChange function works ...

Ways to include multiple pieces of data in a JQuery Mobile List view

Obtaining JSON data (list of available Hotels within a certain distance) and extracting the following information in JSON format: Name of Hotels, Distance of Hotel from our current location, number of rooms. There might be multiple Hotels within the specif ...

Looking for a vertical scrollbar solution for your idangerous vertical swiper?

Incorporating idangerous vertical swiper with two slides in a mobile app through jquery mobile has proven challenging. Specifically, I am struggling to implement a vertical scroll bar in the second slide due to its fixed height and the potential collision ...

Leverage the power of Meteor by incorporating templates to dynamically inject HTML based on an event

I am currently generating HTML using JQuery on an event. However, I believe a better approach would be to use templates in Meteor, especially if the HTML becomes more complex. Template.example.onRendered(function() { paper.on({ 'cell:mous ...

Struggling to execute an AJAX request in JavaScript

I am a beginner in .Net development and I am trying to make a call to the client's server. When I test the code using POSTMAN, it works fine. However, when I use the same code/headers in JavaScript, I do not get the desired result. Here is the code I ...

Transferring array data between classes

Hello, I'm currently learning ReactJs and facing a challenge where the array values are not showing up in the body. class App extends React.Component{ render(){ let arr = ["one", "two"] arr.map(n => <Append val={n}/>) return ...

Issue with column filtering in jQuery DataTables using server-side preprocessing

I'm having issues with the column filter in datatables when using server-side preprocessing. The datatable with column search is not functioning properly. Below is a sample of the code. Could you please provide it in jsfiddle or another platform? Any ...

What benefits come from dynamically loading and unloading JavaScript and CSS stylesheets?

Introduction: Currently, I am in the process of developing a website that will utilize ajax to change content without refreshing the main frame and images every time. The main frame has its own site.css stylesheet. Query 1: Considering the use of a sing ...

"What is the best way to send a stateful array from a child component to a parent component using React Hooks

Within my CreateArea component, I collect user input data and store it in a local state array called notes using setNote. My goal is to display multiple Note components below the CreateArea component, with each component corresponding to an item in the no ...

Using AngularJS, call the $http function in response to another HTTP request

I recently started working with angular JS and I encountered a problem while trying to implement $http within the response of another $http call. My problem is that when I make a $http call within the response of another $http call, the data is not displa ...

Find elements that are not contained within an element with a specific class

Imagine having this HTML snippet: <div class="test"> <div class="class1"> <input type="text" data-required="true"/> </div> <input type="text" data-required="true"/> </div> I'm looking to select ...

Data object constructor is not triggered during JSON parsing

Currently, I am retrieving data from a server and then parsing it into TypeScript classes. To incorporate inheritance in my classes, each class must be capable of reporting its type. Let me explain the process: Starting with the base class import { PageE ...

Switch out a section of the web address with the information from the button to

Before we begin: Check out this Fiddle My current goal is to create a functionality where clicking a button will replace the # in a given link with the text entered in a text box, and then redirect the user to that modified link. http://www.twitch.tv/#/ ...

How to retrieve a specific value using jQuery based on the name attribute

I'm having an issue retrieving the selected value from the menu and assigning it to the `country` variable. Whenever I try, I keep encountering the error: No parameterless constructor defined. The `UpdateClient` function is triggered by clicking on t ...

Unlocking the secrets of parsing JSON within a script tag using Laravel and AngularJS

I am facing some confusion as I attempt to use JSON with Angular and Laravel (v5.2.11) Here is my plan: 1. Send JSON to a blade file 2. Retrieve JSON within a script tag and assign it to a variable 3. Display each data In order to avoid duplicating ...

I'm having trouble with my form submission using AJAX, as it's not echoing

I am currently testing the submission of a form using Ajax (submitting to my own page "new1.php"). What I am aiming for is to have the first and last name echoed after clicking the submit button. However, I am not seeing the first and last name displayed ...

The list attribute in AngularJS seems to be malfunctioning when used in Internet Explorer 11

My current issue involves using the 'find' method within a scope. While it works perfectly fine in Chrome, there seems to be compatibility issues with Internet Explorer 11. How can I resolve this and make it work smoothly on IE 11? $scope.NameLi ...

Exploring the hover effects on Kendo charts and series

I have encountered an issue with my kendo chart. The series hover works fine when the mouse hovers over the serie, but I am facing a problem where the value in the line does not appear as expected. I am unsure of why this is happening. $("#chart1").data(" ...

Setting a random number as an id in the constructor in Next JS can be achieved by generating a

What steps can be taken to resolve the error message displayed below? Error: The text content does not match the HTML rendered by the server. For more information, visit: https://nextjs.org/docs/messages/react-hydration-error Provided below is the code i ...