TanStackT
TanStackโ€ข3y agoโ€ข
6 replies
awake-maroon

useQueries - Accessing meta information in errors

Using V4

Hey ๐Ÿ‘‹
I've tried finding resources on this but came up short.
I'm somewhat inspired by the v5 version of useQueries and combine.

Say I have a functionality that allows to get customers in multiple systems and then combining the final answer into one long list of customers.

I have a simple hook as a wrapper around a query as such;
export const useCustomerQueries = () => {
 const queries = useQueries({
    queries: systems.map((s) => ({
      queryKey: ['customers', s],
      queryFn: () => fetchCustomers(s),
      meta: { system: s },
      ...
    })),
  });

  const data = R.filter(
    queries.flatMap((q) => q.data?.customers),
    R.isDefined
  );

  return {...}
}


Okay so far so good, all customers are being aggregated into a single list.
However we have no error handeling - okay so we add a way to retrieve the errors too.

...method
const errors = R.filter(
  queries.map((q) => q.error),
  R.isDefined
);
...


But now - as we display a list of errors in the UI, we have no idea where this error came from, just that it happened.

We have our meta field on the queries which define the system we're working with, but I see no way to extract the meta field on a query result.

The best I can come up with is doing something like this;
...method
const cache = useQueryClient().getQueryCache();
const errors = cache
  .findAll(['customers'], {
    type: 'active',
    predicate: (q) => !!q.state.error,
  })
  .map((q) => ({ ...q.state.error, meta: q.meta }));
...

Is this approach fine? It feels a little odd to rely on the Query Cache when I am defining my queries a few lines above... Is there a simpler approach that I am missing?
Thanks.

Stackblitz example:
https://stackblitz.com/edit/stackblitz-starters-kov63e?file=src%2Fquery.ts
StackBlitzEmil Dyrhoi
React + TypeScript starter project
Multi Query Example w/ meta aware errors - StackBlitz
Was this page helpful?