TRPC基于动态URL的查询

huangapple go评论65阅读模式
英文:

TRPC query based on dynamic url

问题

Using TRPC 和 Next JS,我想基于动态URL查询单个帖子,而不使用SSR或SSG。唯一有效的方法我发现是将 router.query.id 添加为 as string,但这会导致TRPC错误(错误仅在首次加载时出现),因为对于初始加载,router.query.id 是一个空对象而不是字符串。是否有一种方法可以避免初始TRPC错误?

import { useRouter } from "next/router";
import { api } from "~/utils/api";

const SinglePost = () => {
  const router = useRouter();
  const { data } = api.post.getById.useQuery({
    id: router.query.id as string,
  });

  return (
    <div>
      {data}
    </div>
  );
};

export default SinglePost;
英文:

Using TRPC and Next JS I want to query a single post based on a dynamic url without using SSR or SSG. Only method I found to work is to add as string to router.query.id but this results in a TRPC error (the error only occurs on the first load), because router.query.id is an empty object for the initial load not a string. Is there a way to do this without the initial TRPC error?

import { useRouter } from &quot;next/router&quot;;
import { api } from &quot;~/utils/api&quot;;

const SinglePost = () =&gt; {
  const router = useRouter();
  const { data } = api.post.getById.useQuery({
    id: router.query.id as string,
  });

  return (
    &lt;div&gt;
      {data}
    &lt;/div&gt;
  );
};

export default SinglePost;

答案1

得分: 1

我修改了我的查询如下:

const { data } = api.post.getById.useQuery(
    {
      id: router.query.id as string,
    },
    { enabled: !!router.query.id}
  );

所以它只会在 router.query.id 不是一个空对象时启动。

英文:

I modified my query like this:

const { data } = api.post.getById.useQuery(
    {
      id: router.query.id as string,
    },
    { enabled: !!router.query.id}
  );

so it will only start when router.query.id is not an empty object.

答案2

得分: 0

I guess having a default value may be enough in your case

  const defaultId = 'blah/blah/blah'
  const { data } = api.post.getById.useQuery({
    id: router.query.id ?? defaultId,
  });
英文:

I guess having a default value may be enough in your case

  const defaultId = &#39;blah/blah/blah&#39;
  const { data } = api.post.getById.useQuery({
    id: router.query.id ?? defaultId,
  });

huangapple
  • 本文由 发表于 2023年4月10日 18:33:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定