useQueries()
このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →
useQueriesフックを使用すると、単一のフック呼び出しで可変数のクエリを同時に取得できます。
このフックの主な用途は、通常同じタイプの複数のクエリを取得することです。例えば、TODOアイテムのIDリストを取得した後、useQueriesフック内で各IDをマップ処理し、各TODOの詳細を取得するbyIdエンドポイントを呼び出すことができます。
useQueriesフックで複数のタイプを取得することは可能ですが、suspenseオプションを使用しない限り、複数のuseQuery呼び出しと比べて大きな利点はありません。useQueriesはサスペンスを並列でトリガーできるのに対し、複数のuseQuery呼び出しは連鎖的に処理されるためです。
使用方法
useQueriesフックは@tanstack/queryのuseQueriesと同じものです。唯一の違いは、queries配列を持つオブジェクトを渡す代わりに、tプロキシを受け取りクエリの配列を返すコールバック関数を渡す点です。
httpBatchLinkまたはwsLinkを使用している場合、以下の処理はサーバーへのHTTPリクエストを1回だけにまとめます。さらに、基盤となるプロシージャがPrismaのfindUnique()のようなものを使用している場合、自動的にバッチ処理され、データベースクエリも厳密に1回だけ実行されます。
tsximport {trpc } from './utils/trpc';constComponent = (props : {postIds : string[] }) => {constpostQueries =trpc .useQueries ((t ) =>props .postIds .map ((id ) =>t .post .byId ({id })),);return <>{/* [...] */}</>;};
tsximport {trpc } from './utils/trpc';constComponent = (props : {postIds : string[] }) => {constpostQueries =trpc .useQueries ((t ) =>props .postIds .map ((id ) =>t .post .byId ({id })),);return <>{/* [...] */}</>;};
個々のクエリへのオプション指定
配列内のクエリ呼び出しの第二パラメータとして、enabled、suspense、refetchOnWindowFocusなどの通常のクエリオプションを渡すこともできます。利用可能なすべてのオプションの詳細については、tanstack useQueryドキュメントを参照してください。
tsximport {trpc } from './utils/trpc';constComponent = () => {const [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }, {enabled : false }),t .greeting ({text : 'world' }),]);constonButtonClick = () => {post .refetch ();};return (<div ><h1 >{post .data &&post .data .title }</h1 ><p >{greeting .data ?.message }</p ><button onClick ={onButtonClick }>Click to fetch</button ></div >);};
tsximport {trpc } from './utils/trpc';constComponent = () => {const [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }, {enabled : false }),t .greeting ({text : 'world' }),]);constonButtonClick = () => {post .refetch ();};return (<div ><h1 >{post .data &&post .data .title }</h1 ><p >{greeting .data ?.message }</p ><button onClick ={onButtonClick }>Click to fetch</button ></div >);};
コンテキスト
オプションでReact Queryコンテキストを渡し、デフォルトを上書きすることもできます。
tsxconst [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }),t .greeting ({text : 'world' })],myCustomContext ,);
tsxconst [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }),t .greeting ({text : 'world' })],myCustomContext ,);