简体   繁体   English

尝试在没有互联网连接的情况下使用 tRPC 和 T3 堆栈进行编码

[英]Trying to code using tRPC and T3 stack with no internet connection

What about tRPC or the T3 stack breaks when trying to code offline?尝试离线编码时 tRPC 或 T3 堆栈中断怎么办? My console.log gets called when online, but when I try to code offline the procedure doesn't get called.我的 console.log 在线时被调用,但当我尝试离线编码时,该过程不会被调用。

router.ts

    export const exampleRouter = router({
      hello: publicProcedure
        .input(z.object({ text: z.string().nullish() }).nullish())
        .query(({ input }) => {


          console.log("WHY DON'T I GET CALLED WHEN OFFLINE???");


          return {
            greeting: `Hello ${input?.text} `,
          };
        }),
    });


index.tsx:

  const hello = trpc.example.hello.useQuery({ text: "World" });

  return (
      <>     
        ...
        {hello.data ? <p>{hello.data.greeting}</p> : <p>Loading..</p>}
      </>
  );

tRPC does not directly call your procedure like a function, it's just an additional layer around your API calls that provides amazing DX and typing based on your procedure definitions. tRPC 不会像函数一样直接调用您的过程,它只是围绕您的 API 调用的附加层,可根据您的过程定义提供惊人的 DX 和类型。 In reality it's still making a network request to your procedure, so if you're offline that's not going to happen.实际上,它仍在向您的程序发出网络请求,因此如果您处于离线状态,那将不会发生。

Since the tRPC client uses React Query under the hood, you can take advantage of caching and RQ's offline capability, but you're still not going to be able to hit your endpoint when offline.由于 tRPC 客户端在后台使用 React Query,您可以利用缓存和 RQ 的离线功能,但您仍然无法在离线时访问您的端点。

J. Sheets' answer pointed me in the right direction. J. Sheets 的回答为我指明了正确的方向。 There was a simple fix:有一个简单的修复:

 const hello = trpc.example.hello.useQuery(
    { text: "from tRPC" }
    { networkMode: "always" } <== the fix
  );

More info: https://tkdodo.eu/blog/offline-react-query https://tanstack.com/query/v4/docs/react/guides/network-mode更多信息: https ://tkdodo.eu/blog/offline-react-query https://tanstack.com/query/v4/docs/react/guides/network-mode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM