Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

259
Visualizações
How to add an newly fetched data to an existing array (Js, VueJs)

I have some pagination on an Api route which was used to fetch the post's data.

When the pagination is on page 2, I would like to add the fetched data from the page and add to the existing array.

Function used to fetch the data

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 };
                }
            });
    };

So when the page is 2 onward, the fetched data will add to the existing array.

The result if I used posts.value = { ...posts.value, ...response.data };

The id start from 51 instead of 1 - 100.

The id start from 51 instead of 1 - 100.

I have also tried posts.value = [ ...posts.value, ...response.data ]; but returned

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 look like this

enter image description here

post.value look like this

enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could do this with a cache to provide more control over how much data accumulates on the client. This answer provides a reasonable looking LRU cache. Combining it with your api might look like this...

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 markup would show the current value of posts. Whatever user event that triggers your paging would do this...

// in an async method
this.posts = await getPosts(pageComputedFromUI);

This would have about the same effect as your solution (which caches everything and never expels anything), but with the benefit of memory kept under your control -- and at the cost of more network requests.

about 4 years ago · Juan Pablo Isaza Relatório

0

I have found the solution,

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,
                    data: [...posts.value.data, ...response.data.data],
                };
            }
        });
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda