TanStackT
TanStack3mo ago
4 replies
popular-magenta

Combined Queries Best Practice

Still struggling with the best way to set this up. I have queries from multiple different accounts but for the same data, and I want to unify them into a collection.

This seems the simplest, and works:
    const queries = useMemo(() => createQueryDefinitions(accounts), [accountsHash])
    const eligibleRolesQuery = useQueries({
        queries,
        combine: result => {
            return {
                data: result.flatMap(r => r.data ?? []),
                isLoading: result.flatMap(r => r.isLoading),
            }
        },
    })

    const collection = useMemo(
        () =>
            createCollection(
                queryCollectionOptions({
                    queryKey: ['pim', 'eligibleRoles', eligibleRolesQuery.data],
                    queryFn: async () => eligibleRolesQuery.data,
                    refetchInterval,
                    queryClient,
                    getKey: role => role.id,
                })
            ),
        [accountsHash, queryClient]
    )


However it results in a new query each time the source data changes and my devtools is littered with it.

I was thinking something where I make the query key just 'pim','eligibleRoles', and whenever the depending queries update their data, to trigger an invalidation on the dependent collection query. Might result in a lot of re-queries but the collection will dedupe those and if data hasn't changed, nothing will trigger at the collection level.

Any best practices for this type of situation?
Was this page helpful?