Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue not updating ARRAY properly using unshift

PLEASE HELP ME!!!!!

When my application starts i run an ajax to get all my feeds. These are objects that I then store in my vue variable which is an array.

    props:['id'],
    data(){
        return {
            feedData: []
        } 
    },
    created(){
        axios.get('/feeds/'+this.id).then(response =>{
            this.feedData = response.data.data;
        });
    }

After that when the user types and sends a new post i store the new post in the database and then emit an event to capture the new post from the database. The function for this is in my methods.

    methods: {
        captureFeed: function (feedId) {
            const vm = this;
            axios.get('/feeds/'+this.id+'/'+feedId).then(response =>{
                vm.feedData.unshift(response.data);
                console.log(response.data);
            });
        }
    },

The weird thing is that when i successfully get the new feed i just created and try to add it to the array of feeds using unshift for some reason the very first post of the array is duplicated and i never get to see the new post until i refresh the page. When i check the console log, i can see that i got the new feed. The funny thing is that when i use

vm.feedData.push(response.data);

it works just fine, but the post is at the very bottom which is not what i want!

i have images to show:

first post:

picture of the first post

second post:

picture of the second post

like image 252
Julian Tabona Avatar asked Oct 17 '22 05:10

Julian Tabona


2 Answers

The main issue here is that when you are looping over a component, you are required to use a key.

In 2.2.0+, when using v-for with a component, a key is now required.

That being the case, your template should look like this:

<feed v-for="feed in feedData" :key="feed.id" :feedContent="feed"></feed> 

where feed.id is a unique value in each feed object. This is because of Vue's DOM update strategy. Using a key helps Vue identify which components need to be created/destroyed.

like image 104
Bert Avatar answered Oct 21 '22 03:10

Bert


Are you using the key param in your template? Like this?

 :key="<An ID>"

For instance:

<div  v-for="(item, index) in array" :key="item.id">
  {{index}} - {{item.name}}
</div>
like image 38
Lucas Katayama Avatar answered Oct 21 '22 03:10

Lucas Katayama