when I am making computed property sortedTodoList I am returning the sorted variant of the original todoList, but if sorted option is not selected it parses through the original todoList without any sorting. My problem is that when I make sorting the original list mutates. It is shown not only in UI when changing sort method to none but also in Vue devtools. How to fix it?
import { computed, ref, type Ref } from 'vue'
import { defineStore } from 'pinia'
type Todo = {
name: string,
done: boolean,
flag: number
}
export const useTodoListStore = defineStore('todoList', () => {
const todoList: Ref<Todo[]> = ref([])
const sortType = ref('')
const sortedTodoList = computed(() => {
if (sortType.value === 'flagDescending') {
const sorted = todoList.value.slice()
return sorted.sort((a, b) => {
return a.flag - b.flag
})
}
else if (sortType.value === 'flagAscending') {
const sorted = todoList.value.slice()
return sorted.sort((a, b) => {
return b.flag - a.flag
})
}
else {
return todoList.value
}
})
function addTodo(name: string, flag: number): void {
todoList.value.unshift({
name: name,
done: false,
flag: flag
})
}
function deleteTodo(todo: Todo): void {
todoList.value = todoList.value.filter((t) => todo != t)
}
return { todoList, sortedTodoList, sortType, addTodo, deleteTodo }
}, { persist: true })
I tried changing how I create sorted array but it did not help
Konstantin Gartsman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.