ohffs
1 year ago
42
8
Vue

Replacing a large array

Posted 1 year ago by ohffs

Another in my 'bored on a Friday' series of questions. I was playing around with a little bit of code I have that has a large array of objects in the data() of the component. It loads the data from localStorage on page load and goes off to fetch the current data from an API - basically to give you something to look at as the API call takes about 10 seconds.

However, if I just do :

let newArray = await apiCall();
this.myData = newArray;

then this.myData doesn't seem to get properly replaced. The new data is there, but it's almost like it's a 'shadow'. So for instance you can click an item and it toggles a selected state - but after the api call you need to click the item twice before it 'notices' that it's clicked.

But, if I do :

let newArray = await apiCall();
this.myData = [];
this.$nextTick(() => {
      this.myData = newArray;
});

then it works perfectly. As far as I know Vue should notice that the array has been replaced so the first version should work - so I'm not sure why the second version is needed (I only tried it out of desperation).

Anyone come across this before? I'm guessing it's something to do with the way Vue tries to merge the state of the items - when they are emptied in the current 'tick' it does a full replace on the $nextTick. It seems a bit hacky though :-/

Please sign in or create an account to participate in this conversation.