conlonj25
conlonj25
TTCTheo's Typesafe Cult
Created by conlonj25 on 2/9/2025 in #questions
useSuspenseQuery always called on initial render
Using - t3stack, - trpc 11 - nextAuth 4 The code - I have a protected procedure habit.getByUser - I call useSession and wait for my user session - Once I have the session I render the suspenseful component - Inside the suspenseful component I call my procedure with useSuspenseQuery The problem - This produces a TRPCError: UNAUTHORIZED error on initial render - But it subsequently re-renders once it gets the user session and the procedure executes perfectly Notes - I've tried multiple different ways of preventing the component from rendering immediately but it seems like useSuspenseQuery is always called - I can fix this issue by replacing useSuspenseQuery with a normal useQuery. I just don't know why that works.
"use client";

import { api } from "~/trpc/react";
import { Card } from "~/components/ui/card";
import AddHabitDialog from "./add-habit-dialog";
import EditHabitForm from "./edit-habit-form";
import ListSkeleton from "./skeletons/list-skeleton";
import { Fragment, Suspense } from "react";
import { useSession } from "next-auth/react";

export function MyHabits() {
const [myHabits] = api.habit.getByUser.useSuspenseQuery();

return myHabits ? (
myHabits.map((habit) => (
<Fragment key={habit.id}>
<EditHabitForm habit={habit} />
<hr />
</Fragment>
))
) : (
<p>You have no habits yet.</p>
);
}

export function MyHabitsContainer() {
const { data: session } = useSession();

return (
<Card className="flex flex-col gap-4 p-4">
{session?.user && (
<Suspense fallback={<ListSkeleton />}>
<span>My habits</span>
<MyHabits />
</Suspense>
)}
<AddHabitDialog />
</Card>
);
}
"use client";

import { api } from "~/trpc/react";
import { Card } from "~/components/ui/card";
import AddHabitDialog from "./add-habit-dialog";
import EditHabitForm from "./edit-habit-form";
import ListSkeleton from "./skeletons/list-skeleton";
import { Fragment, Suspense } from "react";
import { useSession } from "next-auth/react";

export function MyHabits() {
const [myHabits] = api.habit.getByUser.useSuspenseQuery();

return myHabits ? (
myHabits.map((habit) => (
<Fragment key={habit.id}>
<EditHabitForm habit={habit} />
<hr />
</Fragment>
))
) : (
<p>You have no habits yet.</p>
);
}

export function MyHabitsContainer() {
const { data: session } = useSession();

return (
<Card className="flex flex-col gap-4 p-4">
{session?.user && (
<Suspense fallback={<ListSkeleton />}>
<span>My habits</span>
<MyHabits />
</Suspense>
)}
<AddHabitDialog />
</Card>
);
}
13 replies