Passing Dynamic Variables & Filters to TRPC results in Hydration Error in Next.JS?

I am trying to make a dashboard where a user can apply a few filters. So they can, for example, request to only see the published posts or the unpublished ones etc. The way I have implemented this is like so:
const Home: NextPage = () => {
const [filterPublishedPosts, setFilterPublishedPosts] = useState(false)

const { data, isLoading } = trpc.item.getAllPosts.useQuery({
text: "from tRPC", filters: {
filterPublishedPosts: filterPublishedPosts
}
});

return (
<main>
<button onClick={() => {
setFilterPublishedPosts(!filterPublishedPosts)
}}>
Show Only Published Posts
</button>
// .... display some data here
</main>
);
};

export default Home;
const Home: NextPage = () => {
const [filterPublishedPosts, setFilterPublishedPosts] = useState(false)

const { data, isLoading } = trpc.item.getAllPosts.useQuery({
text: "from tRPC", filters: {
filterPublishedPosts: filterPublishedPosts
}
});

return (
<main>
<button onClick={() => {
setFilterPublishedPosts(!filterPublishedPosts)
}}>
Show Only Published Posts
</button>
// .... display some data here
</main>
);
};

export default Home;
So I am using useState on the frontend to keep track of what the user wants to see and then pass that down as a variable to trpc. I have 2 questions: 1. Is this the right way to do this? If not, how else do you recommend to interact with my prisma backend via react-query / trpc? 2. Why does it give me an hydration error? Not sure I understand why the data would be different on the server / client in this case? But I get:
Error: Hydration failed because the initial UI does not match what was rendered on the server. See more info here: https://nextjs.org/docs/messages/react-hydration-error
Thanks a lot!
5 Replies
Piotrek
Piotrek•3y ago
There is no such thing as "the right way". I'm using a similar approach in my apps 😉 When it comes to the hydration error, did you manage to resolve it? If not, I would probably check if it still persists when you return something like "Loading..." when isLoading is true
plyglt
plygltOP•3y ago
no, that doesnt help 😦 i also still get the error when not displaying any of the fetched data at all - just having the button in there breaks it. Not sure how thats possible?
Piotrek
Piotrek•3y ago
Are you sure it's in your component? Maybe it's some kind of layout that breaks it
plyglt
plygltOP•3y ago
hmmm, it's a brand new t3 starter project, so I am not sure what else that could be. Figured it out,. It didn't have anything to do with trpc at all. There were some HTML semantics that were wrong which made Next.JS trip up thanks for your help!!
Piotrek
Piotrek•3y ago
No problem
Want results from more Discord servers?
Add your server