Using vuejs3 with composition api, I get data from an api asynchronously.
const accounts = ref([])
const credits = ref([])
const debits = ref([])
const summary = ref([])
const getaccounts = async () => {
try {
// getData is a preformatted axios function
const response = await getData.get(`/myurl/${route.params.month}/${route.params.year}`)
accounts.value = [...response.data.accounts]
debits.value = [...response.data.accounts].filter(obj => {
return obj.amount < 0
})
summary.value = [...debits.value] // DOESN'T WORK
setSummary(summary.value) // THEREFORE ALSO DOESN'T WORK
credits.value = [...response.data.comptes].filter(obj => {
return obj.amount > 0
})
} catch (error) {
console.log(error)
}
}
debits.value
is and Array with 55 objects that looks like so:
const data = [
{ id: 12, amount : 45, category: "alim" },
{ id: 15, amount : 32, category: "misc" },
{ id: 11, amount : 145, category: "bla" },
{ id: 20, amount : 40, category: "misc" },
{ id: 22, amount : 12, category: "alim" },
{ id: 33, amount : 5, category: "bla" }
]
I want to group total amounts per categorie in a new array of objects. Code works in plain javascript and this is what the function setSummary looks like:
const setSummary = (debs) => {
let arr = debs.reduce((acc, item) => {
let existItem = acc.find(({categorie}) => item.categorie === categorie);
if(existItem) {
existItem.amount += item.amount;
} else {
acc.push(item);
}
return acc;
}, [])
resume.value = arr
}
Any manipulation I do on summary.value
affects debits.value
. I know that Vue reactivity is based on Proxy
documentation but I don't see how to clone or deconstruct an object in such a manner that manipulations on the cloned object don't affect the "parent".