T
TanStack2y ago
continuing-cyan

Resources on API data typing, read vs update vs create ?

TLDR: Seeking best practices for handling API data validation and form validation in a React app with Typescript. Full question: We're using React, Typescript, TanStack Query, zod, react-hook-form, etc. The back-end is python, fully separate, cannot use the same typings files. This is a types question, pertaining to API endpoints. We don't want to trigger a zod error if a string is too long from the server, but do want to enforce string length on a form field and any code that does an useMutation. So we have multiple related types for the various things you do with the data. Which leads to type code like this:
const FooCommonSchema = z.object({
title: z.string(),
budget: z.number(),
});

const ReadFooSchema = FooCommonSchema.extend({
uuid: z.string(),
});

const UpdateFooSchema = FooCommonSchema.extend({
title: z
.string()
.min(1, {
message: "Title not be blank",
})
.max(255, {
message: "Title so dang long",
}),
budget: z.number().int().min(1, {
message: "Real money only",
}),
uuid: z.string(),
});
const FooCommonSchema = z.object({
title: z.string(),
budget: z.number(),
});

const ReadFooSchema = FooCommonSchema.extend({
uuid: z.string(),
});

const UpdateFooSchema = FooCommonSchema.extend({
title: z
.string()
.min(1, {
message: "Title not be blank",
})
.max(255, {
message: "Title so dang long",
}),
budget: z.number().int().min(1, {
message: "Real money only",
}),
uuid: z.string(),
});
Looking for best practices in such matters. Our types are getting quite complex and we're looking for ways to simplify. Yes, the above is a simplified example, but we have a lot of repeated code like this.
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?