Tuxer
Tuxer3y ago

query and mutate promise on next

I've followed the guide "Usage with Next.js" and now I only have the useQuery and use useMutation hooks exposed when I want to call a route. How do I also expose the regular query and mutate promises on these routes? Edit: Solution:
const utils = trpc.useContext();

// use it (for example in an event handler)
const someResult = await utils.client.someRouter.someProcedure.query(/* args maybe */);
const utils = trpc.useContext();

// use it (for example in an event handler)
const someResult = await utils.client.someRouter.someProcedure.query(/* args maybe */);
6 Replies
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Tuxer
TuxerOP3y ago
First instantiating mutate from useMutation every time seems to be quite inconvenient. I'm refering to this part of the docs https://trpc.io/docs/quickstart#querying--mutating. I'd like to call query and mutate like described:
const user = await trpc.userById.query('1');
const createdUser = await trpc.userCreate.mutate({ name: 'sachinraja' });
const user = await trpc.userById.query('1');
const createdUser = await trpc.userCreate.mutate({ name: 'sachinraja' });
julius
julius3y ago
The context has the proxy client if that’s what you’re looking for, not sure if that’s better than using the hook though
julius
julius3y ago
Below the table is an example https://trpc.io/docs/useContext#helpers
useContext | tRPC
useContext is a hook that gives you access to helpers that let you manage the cached data of the queries you execute via @trpc/react-query. These helpers are actually thin wrappers around @tanstack/react-query's queryClient methods. If you want more in-depth information about options and usage patterns for useContext helpers than what we provide...
julius
julius3y ago
This is the vanilla client, react uses hooks
Tuxer
TuxerOP3y ago
This looks very promising and exactly what I need. I'll try that. In some cases I think it's more convenient to use the vanilla client instead of hooks, because hooks can not be used everywhere. Okay, it worked as I needed it to. useContext must still be instantiated, direct access via the vanilla client would be even better, but it works via useContext(). Here is how to use it according to the docs:
const utils = trpc.useContext();

// use it (for example in an event handler)
const someResult = await utils.client.someRouter.someProcedure.query(/* args maybe */);
const utils = trpc.useContext();

// use it (for example in an event handler)
const someResult = await utils.client.someRouter.someProcedure.query(/* args maybe */);
Thanks @julius and @cje