Reputation: 65
From the following code, I get the "Unexpected side effect" error. I can't understand what I am doing wrong.
computed: {
sortedlist() {
return this.data.sort((a, b) => {
let modifier = 1;
if (this.currentSortDir === 'desc') {
modifier = -1;
}
if (a[this.currentSort] < b[this.currentSort]) {
return -1 * modifier;
}
if (a[this.currentSort] > b[this.currentSort]) {
return 1 * modifier;
}
return 0;
});
}
}
Upvotes: 0
Views: 73
Reputation: 138606
Any change to the component's data props from within the computed prop is considered a side effect. Since Array.prototype.sort()
sorts the array items in place, the original array is modified in your computed prop, which is a side effect.
A workaround is to use Array.prototype.slice()
to create a copy to sort:
return this.data.slice().sort(...)
Upvotes: 1