tRPCttRPC
Powered by
AvrajA
tRPCβ€’3y agoβ€’
28 replies
Avraj

Is there a way to refetch a query with new parameters?

Hi

I'm using tRPC in a Next.js app and I have a button that a user can click to get the latest data from the server. By default this data is cached in the server because the query is expensive. I've added an optional param/input in my query that looks like this:

guilds: privateProcedure
    .input(
        z
            .object({
                skipCache: z.boolean().optional(),
            })
            .optional()
    )
    .query(async ({ input, ctx }) => {
        // Get data
    });
guilds: privateProcedure
    .input(
        z
            .object({
                skipCache: z.boolean().optional(),
            })
            .optional()
    )
    .query(async ({ input, ctx }) => {
        // Get data
    });


So when
{ skipCache: true }
{ skipCache: true }
is set, the user can bypass the cache and get the latest data. I'm feeling a bit lost however when it comes to the implementation itself. I can't find anything in the docs regarding refetching with new/updated params.

const trpcUtils = trpc.useUtils(); // This will return cached data from the server.

const { data: guilds, error } = trpc.private.guilds.useQuery();

const handleRefresh = () => {
    // The implementation to bypass cached data => { skipCache: true }
}

return <button onClick={handleRefresh}>Refresh</button>
const trpcUtils = trpc.useUtils(); // This will return cached data from the server.

const { data: guilds, error } = trpc.private.guilds.useQuery();

const handleRefresh = () => {
    // The implementation to bypass cached data => { skipCache: true }
}

return <button onClick={handleRefresh}>Refresh</button>


Is this something that's possible?
Solution
What you can do is just to have a skipCache state and pass this to your useQuery.

const [skipCache, setSkipCache] = useState(false);

const {data: guilds} = trpc.private.guilds.useQuery({skipCache});

const utils = trpc.useUtils();

const handleRefresh = () => {
  setSkipCache(true);
  utils.private.guilds.invalidate();
}
const [skipCache, setSkipCache] = useState(false);

const {data: guilds} = trpc.private.guilds.useQuery({skipCache});

const utils = trpc.useUtils();

const handleRefresh = () => {
  setSkipCache(true);
  utils.private.guilds.invalidate();
}
Jump to solution
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

Is there a way to pass parameters to procedure on call?
StivoSStivo / ❓-help
2y ago
Is there a way to alter the query key generated by trpc?
asliwinskiAasliwinski / ❓-help
3y ago