Advice for complex custom hooks
Hey! I’m looking for a good pattern for complex custom hooks. My team is using Orval (https://github.com/anymaniax/orval) to generate TanStack custom hooks for each of our API endpoints. From those generated hooks, I would like to derive results that require >1 of them.
Here’s one example. I’d like to compose the results from two queries.
Ideally, I would like to abstract away the complexity in my own custom hook:
Is there a good pattern for
createMyCustomHook
?
I see two approaches:
1. Build on top of the Orval-generated custom hooks createOrvalCustomHook1
and createOrvalCustomHook2
. With this approach, I’d like to access a unified TanStack state (e.g. an isSuccess
that spans both queries) and query options (e.g. anenabled
flag to trigger both queries).
2. Build a custom query hook from scratch. Create a queryFn
that calls both the query1
and the query2
endpoints and composes the results. With this approach, I would like to leverage the data in the Query Cache for each of those individual queries.
Any guidance would be appreciated!GitHub
GitHub - anymaniax/orval: orval is able to generate client with app...
orval is able to generate client with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in yaml or json formats. 🍺 - GitHub - anymaniax/orval: o...
1 Reply
grumpy-cyan•3y ago
There's a
createQueries
API available in Svelte-Query. It isn't documented for Svelte, but here's React's hook version: https://tanstack.com/query/v4/docs/react/reference/useQueries. I don't have any experience with it however.
You can also check out Svelte's second parameter to writable
as a starting point to create custom writable stores that reference other stores: https://svelte.dev/docs#run-time-svelte-store-writable. I used this in my project to create a writable input that updates writable query options.Overview | TanStack Query Docs
TanStack Query (FKA React Query) is often described as the missing data-fetching library for web applications, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your web applications a breeze.
Motivation
Svelte docs
Complete documentation for Svelte