Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: zod validation fieldErrors type inference #2058

Open
sahandsn opened this issue Feb 19, 2025 · 0 comments
Open

feat: zod validation fieldErrors type inference #2058

sahandsn opened this issue Feb 19, 2025 · 0 comments
Labels
🌟 enhancement New feature or request

Comments

@sahandsn
Copy link

sahandsn commented Feb 19, 2025

Is your feature request related to a problem? Please describe.

when i want to access the field errors, i don't get type suggestion.

for instance in this router:

import { z } from "zod";

import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
import { urls } from "@/server/db/schema";

export const urlRouter = createTRPCRouter({
  createGeneric: protectedProcedure
    .input(z.object({ source: z.string().url() }))
    .mutation(async ({ ctx, input }) => {
      await ctx.db.insert(urls).values({
        source: input.source,
        userId: ctx.session.user.id,
      });
    }),
});

i want to check errors for the input validations:

"use client";

import { useState } from "react";

import { api } from "@/trpc/react";

export function LatestUrl() {
  const [latestUrl] = api.url.getLatest.useSuspenseQuery();

  const utils = api.useUtils();
  const [url, setUrl] = useState("");
  const createUrl = api.url.createGeneric.useMutation({
    onSuccess: async () => {
      await utils.url.invalidate();
      setUrl("");
    },
  });

  return (
    <div className="w-full max-w-xs">
      
      <form
        ...
      >
        ...
        {createUrl.error && (
          <p>{createUrl.error.data?.zodError?.fieldErrors.source}</p>
        )}
         ...
      </form>
    </div>
  );
}

however, source is not suggested when i access createUrl.error.data?.zodError?.fieldErrors.

Describe the solution you'd like to see

if this helper function could read the input fields, the problem would be solved:

/**
 * 2. INITIALIZATION
 *
 * This is where the tRPC API is initialized, connecting the context and transformer. We also parse
 * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation
 * errors on the backend.
 */
const t = initTRPC.context<typeof createTRPCContext>().create({
  transformer: superjson,
  errorFormatter({ shape, error }) {
    return {
      ...shape,
      data: {
        ...shape.data,
        zodError:
          error.cause instanceof ZodError ? error.cause.flatten() : null,
      },
    };
  },
});

Describe alternate solutions

if anyone have other solutions or alternatives, i'd really appreciate it.

Additional information

No response

@sahandsn sahandsn added the 🌟 enhancement New feature or request label Feb 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🌟 enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant