英文:
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 "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;
答案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 = 'blah/blah/blah'
const { data } = api.post.getById.useQuery({
id: router.query.id ?? defaultId,
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论