1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Tanstack Query】[["article","getFive"],{"type":"query"}] data is undefinedのエラー解決

Posted at

はじめに

こんにちは!Halです!
Next.js(app router)とTanstack Queryを利用してSSRを行った際に出たエラーの対処についてまとめます。

問題

tRPC側でちゃんとデータは取得できていますが、Tanstack側でundefindとして処理されてしまっています。

[TRPC] article.getFive took 277ms to execute
Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: [["article","getFive"],{"type":"query"}]
[Error: [["article","getFive"],{"type":"query"}] data is undefined]
 ⨯ unhandledRejection: [Error: [["article","getFive"],{"type":"query"}] data is undefined]
 ⨯ unhandledRejection:  [Error: [["article","getFive"],{"type":"query"}] data is undefined]
 ⨯ [Error: [["article","getFive"],{"type":"query"}] data is undefined] {
  digest: '980909864'
}

何をしていたのか

次の流れでNext.jsとTanstackQueryでSSRをする処理を書いていました。

  • Next.jsのServer ComponentsでTanstack QueryのQueryClient.prefetchQueryを利用してデータをキャッシュ
  • キャッシュをdehydrate関数によりシリアライズを行う, HydrationBoundaryコンポーネントに詰める
  • クライアント側でキャッシュをhydrate関数によりデシリアライズを行う
  • Client Component側でuseSuspenseQueryを利用してキャッシュされたデータを取得

原因

  • TanstackQuery側で、QueryClientを生成した際に指定できるシリアライズとデシリアライズの形式が異なっていました
  • dehydrate時は無指定ですが, hydrate時はデシリアライズにSuperJsonの形式を当てています
  • これによってサーバー側とクライアント側で形式ミスが起こり、undefined扱いとなっていました
query-client.ts
import {
  defaultShouldDehydrateQuery,
  QueryClient,
} from "@tanstack/react-query";
import SuperJSON from "superjson";

export const createQueryClient = () =>
  new QueryClient({
    defaultOptions: {
      dehydrate: {
        // serializeData: ここの指定がなかった!
      },
      hydrate: {
        deserializeData: SuperJSON.deserialize,
      },
    },
  });

おわりに

このエラーに気づくのに、2~3時間ぐらいかかりました。(T_T)

Next.jsとTanstack queryでSSRをしたときの参考記事

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてくださ!
▼▼▼

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?