Son
Son3y ago

correct way to call TRPC inside a function

i want a user to be able to sign after they have a clicked a button but i get a hooks error. can anyone help with this?
10 Replies
Son
SonOP3y ago
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Son
SonOP3y ago
Thank you, i made use of the enabled property, and used refectch() in the component. I’m going to export it into. Custom hook and rejig it. This is the pattern I came up with. I want to call my route when a button is clicked and have access to isLoading, onError etc… I have implemented a pattern using ‘’refetch()’’ but it doesn’t feel ‘correct’ is there a better way of doing this. I will also create a custom hook out of it. ‘’’js const { refetch } = trpc.authDomain.signIn.useQuery( { email: userEmail }, { enabled: false, onError: (e: any) => { console.log('there was an error with the endpoint'); }, } ); async function isEmailVerified() { const response = await refetch(); const verification = response.data; // i want to access isLoading directly without writing many lines of new code which i would have to with this current approach if (verification?.status === 'tryAgain') { console.log('email not verified'); setHasInitiatedSignIn(true); } if (verification?.status === 'ok') { console.log('user can now verify code sent to their email address'); setHasInitiatedSignIn(true); } } Return <button onClick={isEmailVerified}/> ‘’’
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Son
SonOP3y ago
This helped ill try some variation of this for my needs. thanks
julius
julius3y ago
to me signIn is a mutation - not a query.
const MySignInComp = () => {
const { mutate: signIn, isLoading: isSigningIn } = trpc.auth.signin.useMutation({
onSuccess() {
// do something on successful mutation
},
});

return (
<button onClick={signIn}>
{isSigningIn && <Spinner />}
Sign In
</button>
);
};
const MySignInComp = () => {
const { mutate: signIn, isLoading: isSigningIn } = trpc.auth.signin.useMutation({
onSuccess() {
// do something on successful mutation
},
});

return (
<button onClick={signIn}>
{isSigningIn && <Spinner />}
Sign In
</button>
);
};
Son
SonOP3y ago
How would you handle ‘isLoading’
julius
julius3y ago
isLoading prop on the useMutation (updated code snippet)
Son
SonOP3y ago
Ill try this approach, thanks
mark salsbery
mark salsbery3y ago
You’ll find it much easier than fighting useQuery I reckon 😉

Did you find this page helpful?