next.jsreact-querytrpc.io

Invalidating data with trpc.useContext() causing a infinite loop


I have am having a problem invalidating my data causing it to run nonstop in a loop and cannot see the reason why it is happening or what I need to do to fix it as I am still new with trpc.

Here is my component where the invalidate is being used:

const ShowUsers = ({ householdId }: ShowUserProps) => {
  const inviteRoute = api.useContext().household;
  
  const getInviteList = api.household.getInviteList.useQuery(
    { householdId },
    {
      onSuccess: () => {
        // void inviteRoute.invalidate(); <-- when uncommented, it runs nonstop
      },
    }
  );

  const deleteInvite = api.invite.deleteInvite.useMutation();

  const { data: sessionData } = useSession();

  return (
    <div>
      <h2>Invited</h2>
      {getInviteList.data &&
        getInviteList.data[0]?.invitedList.map((invite, i) => (
          <div key={i} className="flex gap-3">
            <p>{invite.email}</p>
            {sessionData?.user.role === "ADMIN" && (
              <p onClick={() => deleteInvite.mutate({ email: invite.email })}>
                X
              </p>
            )}
          </div>
        ))}
    </div>
  );
};

and here are the trpc functions being used on the backend:

getInviteList: protectedProcedure
    .input(z.object({ householdId: z.string() }))
    .query(async ({ ctx: { prisma }, input }) => {
      const inviteList = await prisma.household.findMany({
        where: {
          householdId: input.householdId,
        },
        select: {

          invitedList: true,
        },
      });

      return inviteList;
    }),

and this is the function that is called to initiate the invalidation:

deleteInvite: protectedProcedure
    .input(z.object({ email: z.string() }))
    .mutation(async ({ ctx, input }) => {
      await ctx.prisma.invite.delete({
        where: {
          email: input.email,
        },
      });
    });

Other than running nonstop, the function works as intended and removed the invite from the list as soon as it is clicked.

Am I needing to somehow target the specific invite being deleted in the invalidation object?

Thanks!

Edit: I changed the invalidation call to

void inviteRoute.getInviteList.invalidate();

to target the specific route but I am still getting the same problem.


Solution

  • I realized that I was running the invalidation on the wrong function, I should've been calling it onSuccess of the deleteInvite call, not the getInviteList call.