T
tRPC

Modify the payload before mutating

Modify the payload before mutating

RRyan9/28/2023
I have a specific mutation hook that is used all throughout my app, and inside of the hook I want to modify the payload before it is sent to the server (to read something from local storage and add it to payload). Is this possible? I can't seem to find a way to do this. There also isn't a way AFAIK to modify the mutationFn with the nextjs adapter. My only solution would be redefining mutate and mutateAsync that are modified to do this preprocessing. Thanks!
Nnlucas9/28/2023
What's the actual use case?
RRyan9/28/2023
I have a hook wrapped around this specific useMutation that is called from a few different places in my app. I need it to pass some UTM params stored in my local storage along with the payload, but don't want to have to remember to always include the params when I call the mutation. Ideally in the hook (within the mutate fn) I can add the utms
Nnlucas9/28/2023
If you have a custom hook why not just wrap the mutation function and return it? That way it’s all static typed Alternatively wouldn’t UTM params often be better to include as headers? You can easily attach them as headers from the client you create
RRyan9/28/2023
I would but I would need to separately wrap both mutate and mutateAsync since I would need to modify the payload on both. Yeah I have a few more non utm param things, like referral code etc.
Nnlucas9/28/2023
If you have some global middlewarish solution on the frontend, you would be modifying requests without any type safety. I would just wrap the 2 functions, it's safe and not that laborious
RRyan9/28/2023
I wouldn't be losing type safety necessarily, cause the items that I want to add in preprocessing are all optional items, so mutate would still infer its original payload type This is what I ended up doing.. not sure I like it though, also not 100% sure what the impications of using the ProxyClient is on the cache, if any.
export const useVerifyCode = () => {
const key = getQueryKey(trpc.auth.verifyCode);

const mutationFn = async (block: RouterInputs['auth']['verifyCode']) => {
const maybeReferralCode = storage.getReferrerCode();
const maybeUTM = storage.getUTM();
const utmObject = maybeUTM ? JSON.parse(maybeUTM) : {};
// safe parse with zod
const utmValidation = zodUtm.safeParse(utmObject);
const validatedUtm = utmValidation.success ? utmValidation.data : {};

const extendedBlock = {
...block,
referralCode: maybeReferralCode,
...validatedUtm,
};

return trcpProxyClient.auth.verifyCode.mutate(extendedBlock);
};

const mutation = useMutation({
mutationFn,
mutationKey: key,
onSuccess(data) {
storage.setAccessToken(data.accessToken);
storage.setRefreshToken(data.refreshToken);

identify(data);
},
});

return mutation;
};
export const useVerifyCode = () => {
const key = getQueryKey(trpc.auth.verifyCode);

const mutationFn = async (block: RouterInputs['auth']['verifyCode']) => {
const maybeReferralCode = storage.getReferrerCode();
const maybeUTM = storage.getUTM();
const utmObject = maybeUTM ? JSON.parse(maybeUTM) : {};
// safe parse with zod
const utmValidation = zodUtm.safeParse(utmObject);
const validatedUtm = utmValidation.success ? utmValidation.data : {};

const extendedBlock = {
...block,
referralCode: maybeReferralCode,
...validatedUtm,
};

return trcpProxyClient.auth.verifyCode.mutate(extendedBlock);
};

const mutation = useMutation({
mutationFn,
mutationKey: key,
onSuccess(data) {
storage.setAccessToken(data.accessToken);
storage.setRefreshToken(data.refreshToken);

identify(data);
},
});

return mutation;
};

Looking for more? Join the community!

T
tRPC

Modify the payload before mutating

Join Server
Recommended Posts
is there a simple boilerplate that has everything ready to deploy?For example nodemon, reading the port for .env, etc. (I don't know if that's how it is haha) I use Context is not fully globally accessed? [ probably newbie question ]I create a context in the based procedure, but It's undefined in the procedure based on it. ~~Also Using tRPC for server to server requestsHey everyone! The start up I’m at recently deployed a server separate from our main server. Our mainReferenceError: FormData is not definedI am using the experimental form data as shown in the examples and it works correctly on my machine,TRPCError that has TRPCError as causeHaving some troubles with error handling, specifically, my errors are double-wrapped in a TRPCErrorHow do you make use of custom input validation?I have an input validation middleware, to parse my input based on some values in ctx. ``` export fuWhy useQuery() tries to refetch when error occurs while useMutation() doesn't?I'm using the T3 stack. ```test: publicProcedure.input(z.string().min(5)).query(async () => { Lambda WITHOUT API Gateway (Lambda Function URL)Anyone know how to make this work?In a monorepo can I have 2 packages each one with different trpc server, and use both in 1 app?I want to create 2 different APIs, and in my monorepo I have several apps, in some I want to use botHave you used electron-trpc? how does it work for you? Do you recommend it?https://www.electron-trpc.dev/ Thankstrpc error fetch failedplease helpHow to type a helper function to standardise loading and error states with a useQuery call?I am trying to standardize handling of error and loading states. I'd like to have one function/compoTypeScript Issue: router.createCaller Implicitly has Return Type "any"Hello everyone, I'm currently working on a project using tRPC and Prisma. However, I've run into an2 react renders causing 4 trpc query executesI see that my nextjs page is rendering twice on initial load. This is causing 4 executes of my querySuspend subscriptions when app is in backgroundWhen using React Native, subscriptions stay open even when the app is in the background. While this Callbacks in Consecutive MutationsI seem to be running into this issue https://tanstack.com/query/v4/docs/react/guides/mutations#consereturn type of a query endpointHello I currently have a trpc endpoint: ```ts const customInstances = api.customInstance.userCustTroubleshooting 'Type Instantiation Is Excessively Deep' Error in Next.js Project with TRPC IntegratI am using the table and pagination for listing data, just as the awesome developer did in 'https://