I am currently in the process of replicating a real-life example of my code. In the actual code, this line represents a component
that will continuously fetch an endpoint every few seconds, retrieving a random array of length "n"
, encapsulated within the variable myData
.
<div v-for="item in addingData(myData)"> <!-- In the live code, "myData" is the response from an endpoint based on setInterval, returning data like [{id:1},{id:2}] -->
{{ item.id }}
</div>
To simulate dynamic changes in the response stored in myData
, I am utilizing the setTimeOut
function.
mounted() {
setTimeout(() => {
console.log('First data');
this.myData = [{ id: 3 }, { id: 2 }, { id: 1 }];
setTimeout(() => {
console.log('second data');
this.myData = [{ id: 4 }, { id: 4 }];
setTimeout(() => {
console.log('Third data');
this.myData = [];
}, 3000);
}, 3000);
}, 2000);
},
The goal is to present a concatenated list of unique data items each time new data is received in myData
. This behavior is achieved by calling the function addingData(myData)
which performs the concatenation operation. The function
v-for="item in addingData(myData)
utilizes the variable auxData
for this purpose.
The issue arises where the addingData function is unintentionally triggered twice when new data is received. How can this redundancy be prevented?
In terms of performance, the expected output in the console.log
should resemble the following:
https://i.sstatic.net/c5DKg.png
What leads to this re-rendering and what strategies can be employed to mitigate it?
This is the link to the live code:
https://stackblitz.com/edit/vue-l7gdpj?file=src%2FApp.vue
<template>
<div id="app">
<div v-for="item in addingData(myData)">
{{ item.id }}
</div>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';
export default {
name: 'App',
data() {
return {
myData: [],
auxData: [],
};
},
mounted() {
setTimeout(() => {
console.log('First data');
this.myData = [{ id: 3 }, { id: 2 }, { id: 1 }];
setTimeout(() => {
console.log('second data');
this.myData = [{ id: 4 }, { id: 4 }];
setTimeout(() => {
console.log('Third data');
this.myData = [];
}, 3000);
}, 3000);
}, 2000);
},
methods: {
addingData(getDataFetch) {
console.log('Entering AddingData', getDataFetch);
if (getDataFetch.length !== 0) {
if (this.auxData.length === 0) {
//Adding initial data
this.auxData = getDataFetch;
} else {
//Preventing duplication of values
getDataFetch.forEach((item) => {
const isNewItem = this.auxData.find((itemAux) => {
return item.id === itemAux.id;
});
if (!isNewItem) {
//Adding new data
this.auxData.unshift(item);
}
});
}
} else {
//Returning empty array if no data present
return this.auxData;
}
},
},
};
</script>