Skip to content

Instantly share code, notes, and snippets.

@johannschopplich
Last active October 20, 2022 06:50
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save johannschopplich/90dbdb79d6bef990c4b5e0890cc049e5 to your computer and use it in GitHub Desktop.
Fetch data with typed response from Zog schema
// Create a schema for a post
const Post = z.object({
slug: z.string(),
content: z.string(),
});
// Create a schema for a post collection
const Posts = z.array(Post);
// Fetch a post by slug with the correct typed response
const fetchWithSchema = async <TSchema extends z.ZodType>(
schema: TSchema,
url: string
): Promise<z.infer<TSchema>> => {
const result = await fetch(url).then((res) => res.json());
return schema.parse(result);
};
const posts = fetchWithSchema(Posts, "/posts");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment