Asked By: Anonymous
I have two stores:
export const custom_items = writable([]);
export const another_items = writable([]);
Both of them have array of objects, the object looks like this (of course, values are different):
{
id: 123
amount: 123
price: 123
}
I would like to make my own derived variable which will hold total amount of the both stores "custom_items" and "another_items". How can i do that?
I can do it only by this code but it is not reactive:
function get_total_amount() {
let total = 0;
get(custom_items).every((item) => {
total += item.amount;
})
get(another_items).every((item) => {
total += item.amount;
})
return total;
}
There must be a better way, i’ve heard about derived stores but I don’t know how to use it in this case.
Solution
Answered By: Anonymous
Use a derived store:
export const custom_items = writable([]);
export const another_items = writable([]);
const get_total = items => items.flat().map(x => x.amount).reduce((t, x) => t + x, 0)
export const total = derived(
[custom_items, another_items], // deps
items => get_total(items) // [...values] => derived_value
)