Skip to content

Instantly share code, notes, and snippets.

@rikukissa
Created March 17, 2025 12:25
Show Gist options
  • Save rikukissa/fd1b35f83df284214e7d9615e94c890d to your computer and use it in GitHub Desktop.
Save rikukissa/fd1b35f83df284214e7d9615e94c890d to your computer and use it in GitHub Desktop.
export function useEventAction<P extends DecorateMutationProcedure<any>>(
trpcProcedure: P
) {
const eventConfigurations = useEventConfigurations()
const allOptions = {
...trpcProcedure.mutationOptions(),
...queryClient.getMutationDefaults(trpcProcedure.mutationKey())
}
// mutationFn will be removed at this stage to ensure it has been specified in a serializable manner under /procedures. This ensures early error detection
// without explicitly testing offline functionality.
const { mutationFn, ...mutationOptions } = allOptions
const actionType = mutationOptions.meta?.actionType as ActionType | undefined
if (!actionType) {
throw new Error(
`No event action type found. This should never happen, ${JSON.stringify(
mutationOptions
)}`
)
}
const mutation = useMutation<
inferOutput<P>,
TRPCError,
inferInput<P>,
unknown
>({
...mutationOptions
})
type Options = MutateOptions<
inferOutput<P>,
TRPCError,
inferInput<P>,
unknown
>
return {
mutate: (params: inferInput<P>, options: Options) => {
const localEvent = findLocalEventData(params.eventId)
const eventConfiguration = eventConfigurations.find(
(event) => event.id === localEvent?.type
)
if (!eventConfiguration) {
throw new Error('Event configuration not found')
}
const fields = getActiveActionFields(eventConfiguration, actionType)
const overridenOptions: Options = {
...allOptions,
onSuccess: async (data, variables, context) => {
await allOptions.onSuccess?.(data, variables, context)
await options.onSuccess?.(data, variables, context)
},
onError: async (data, variables, context) => {
await allOptions.onError?.(data, variables, context)
await options.onError?.(data, variables, context)
},
onSettled: async (data, variables, context) => {
await allOptions.onSuccess?.(data, variables, context)
await options.onSuccess?.(data, variables, context)
}
}
return mutation.mutate(
{
...params,
data: stripHiddenFields(fields, params.data)
},
overridenOptions
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment