Adding a recently retrieved data to a current array in JavaScript and Vue.js

API route is fetching data, and I have implemented pagination to fetch post data.

On page 2 of pagination, I want to append the fetched data to the existing array.

Function utilized for data fetching

const posts = ref([]);
const page = ref(1);

const getPosts = async (page) => {
        await axios
            .get("/api/explore/gallery/?page=" + page)
            .then((response) => {
                if (page === 1) {
                    posts.value = response.data;
                } else {
                    posts.value = { ...posts.value, ...response.data };
                }
            });
    };

From page 2 onwards, the fetched data will be added to the existing array.

Outcome with

posts.value = { ...posts.value, ...response.data };

https://i.sstatic.net/gfZKv.png

The id now starts from 51 instead of 1 - 100.

I also attempted

posts.value = [ ...posts.value, ...response.data ];
but encountered

PostApi.js:12 Uncaught (in promise) TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
    at _nonIterableSpread (PostApi.js:12:39)
    at _toConsumableArray (PostApi.js:10:131)
    at eval (PostApi.js?c0c4:15:21)

response.data has this structure

https://i.sstatic.net/1Ysrh.png

post.value appears like this

https://i.sstatic.net/O6IoD.png

Answer №1

To optimize the amount of data stored on the client side, consider implementing a cache system. A useful LRU cache solution can be found in this answer. Integration with your API could be done as follows...

const cache = new LRU(8);

const getPosts = async (page) => {
    const result = cache.get(page);
    if (result) return Promise.resolve.result;
    return await axios
        .get("/api/explore/gallery/?page=" + page)
        .then((response) => {
            cache.set(page, response.data);
            return response.data;
        });
};

Your webpage should display the current value of posts. The paging action triggered by the user would look something like this...

// inside an async function
this.posts = await getPosts(pageComputedFromUI);

This approach ensures better memory management compared to caching everything indefinitely, though it does involve more frequent network requests.

Answer №2

After much trial and error, I have finally discovered the solution:

const retrievePosts = async (pageNumber) => {
    await axios
        .get("/api/explore/gallery/?page=" + pageNumber)
        .then((response) => {
            if (pageNumber === 1) {
                posts.value = response.data;
            } else {
                posts.value = {
                    ...posts.value,
                    data: [...posts.value.data, ...response.data.data],
                };
            }
        });
};

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

What is the process of adding a div to the left side of the parent element in AngularJS

I am trying to append the code on the left side of the click. My current controller code looks like this: demo.$inject = ['$scope']; demo.directive("boxCreator", function($compile){ return{ restrict: 'A', l ...

Observing the closing of a modal window from a different controller in AngularJS

Within my main controller, I have a function called $scope.showDialog: $scope.showDialog = function(ev) { $mdDialog.show({ controller: 'DialogController', templateUrl: 'partials/dialog.tmpl.ejs', targetEvent: ev ...

Flickering issue with Chart.js chart persists upon reopening the page

Utilizing mustache.js, I am injecting a view file into a designated <div>. Within this view, I have incorporated a canvas element situated inside a specific div, showcasing a chart created with Chart.js. <div> <canvas id="gesundheitsve ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

Decoding JSON data with JavaScript

My JavaScript code is giving me trouble. I am using an ajax method that returns a JSON string like this: { "ObjectResponse": { "Operation": "OK", "Response": "SUCCESS", "Message": "List of AAA Found", "List": [ { "keySourc ...

What is the process for generating a GET request for selected checkboxes and subsequently showcasing the data on an HTML webpage?

Currently working on an app project and need assistance with implementing a feature. I have successfully set up a POST method for the checkboxes that are checked, but I am unsure how to retrieve this data and display it on my HTML page using a GET method ...

Issue: Utilized more hooks than in the previous render cycle

After the initial load of a component that renders and makes data calls on the client side, everything works fine. However, when clicking a "see more" button to make another call, an error occurs in the console indicating that there are too many hooks be ...

Delete the span element if the password requirements are satisfied

I am implementing password rules using span elements. I aim to dynamically remove each span that displays a rule once the input conditions are met. Currently, I have succeeded in removing the span related to the minimum length requirement but I am unsure h ...

Dropdown selection returning the text value instead of the designated value

Is it possible to retrieve the text "Region 1" instead of just the value '1' from a dropdown menu in PHP? <select name = 'region' id = 'region'> <option value = '1'>Region 1</option> <select&g ...

The error "ReferenceError: process is not defined in vue 3" is being

<script setup> import puppeteer from 'puppeteer'; const onChange = async () => { // Initializing the puppeteer library const browser = await puppeteer.launch(); // Creating a new page const page = await browser.newPage(); / ...

Tips for retaining the scroll position of a particular page after a postback

I am working on a grid to display data row by row. Each row is displayed using a user control. When I scroll to the bottom of the page and click on a row, it redirects me to a view page for that specific row. However, when I click on the back link, I would ...

Is FIREFOX better with plugins or extensions?

I have created a JavaScript function that changes the colors of images on web pages, specifically to assist colorblind individuals in identifying content. The entire development process was done using JavaScript within the Dreamweaver environment, along w ...

Tips on invoking a scope function depending on an attribute's value

In my application, there are multiple 'save and close' links, each with a unique function triggered when clicked, specified by the directive ng-really-click. This directive confirms closure before executing the designated function. For example: ...

The attempt to update several partial views using Jquery, MVC, and Json is currently malfunctioning

I am facing issues with updating multiple partial views using jQuery, MVC, and JSON. The partial views on my page are not getting updated. Below is the code for my view: Here is the code for my controller: public class GetStudentsController : Controlle ...

Trigger Javascript on 'Nearby' input from Html form

I have a JavaScript code that retrieves the latitude and longitude of users from their device for a local search. Although everything works correctly, I want to make sure the script is only executed if the user specifically selects "nearby" as the locatio ...

The webkitTransitionEnd event fires prior to a repaint or reflow occurring

My goal is to create a progressBar that changes its width when an ajax request is made. I want the ajax callback to only execute after the animation of the progressBar is complete. Here is the code I am using: CSS: #progressBar{ position: fixed; ...

I'm facing an issue where there is no "Access-Control-Allow-Origin" header present. Looking for assistance in converting it to JSONP using the POST method. Can anyone provide guidance?

Even though I have changed it to JSONP, the CORS error is still persisting. Here is the updated code snippet: $.ajax({ type: "POST", url: "<a href="https://api.api.ai/v1/" rel="nofollow noreferrer">https://api.api.ai/v1/</a& ...

The perpetual loop in React context triggered by a setState function within a useEffect block

I'm experiencing an endless loop issue with this context component once I uncomment a specific line. Even after completely isolating the component, the problem persists. This peculiar behavior only manifests when the row is discounted and the browser ...

Use Javascript to display an image based on the date, otherwise hide the div

I'm looking to implement an image change on specific dates (not days of the week, but actual calendar dates like August 18th, August 25th, September 3rd, etc). Here's the div I'm working with: <div id="matchday"> <img id="home ...

What is the best way to implement a dynamic sidebar component using React and Material UI?

I have been attempting to implement a responsive sidebar using React Material Design, but I am struggling to achieve the desired outcome. The main goal is for the page content to remain responsive when the sidebar is opened, without overlapping on the pag ...