T
TanStack2y ago
multiple-amethyst

Getters

Hi, I have a general question regarding vue/pinia/tanstack pattern. Working on a vue app where we have a number of pinia stores in which we store data fetched from our api. Often in the same stores, we have a bunch of computed refs, which are based on the retrieved data. I would like to replace the data fetching and storing/caching of data with Tanstack, but I’m unsure of where best to put these extra getters. Pass a select function maybe? Would love some input. Thanks.
3 Replies
rare-sapphire
rare-sapphire2y ago
In this situation I'd move these getters into separate composables with computed that use data from tanstack.
export function useTodos() {
return useQuery({
queryKey: keys.todos(),
queryFn: getTodos,
});
}

export function useTotalTodos() {
const todos = useTodos();
const totalTodos = computed(() => todos.data?.length);

return {
totalTodos,
}
}
export function useTodos() {
return useQuery({
queryKey: keys.todos(),
queryFn: getTodos,
});
}

export function useTotalTodos() {
const todos = useTodos();
const totalTodos = computed(() => todos.data?.length);

return {
totalTodos,
}
}
there's a slight perf overhead compared to pinia if you're using useTotalTodos across multiple Vue components. but this could be solved by wrapping it in createSharedComposable from vueuse if you want to make it global.
national-gold
national-gold2y ago
select would work well and is not vue specific:
export function useTodos(select) {
return useQuery({
queryKey: keys.todos(),
queryFn: getTodos,
select,
});
}

export function useTotalTodos() {
return useTodos(todos => todos.length)
}
export function useTodos(select) {
return useQuery({
queryKey: keys.todos(),
queryFn: getTodos,
select,
});
}

export function useTotalTodos() {
return useTodos(todos => todos.length)
}
`
multiple-amethyst
multiple-amethystOP2y ago
Thanks, will try that out. I guess we can live with that overhead. Creating a shared composable seems a lot like creating a pinia store... Thanks, will try this pattern too and see if it "fits"...

Did you find this page helpful?