Last active
October 20, 2022 06:50
-
-
Save johannschopplich/90dbdb79d6bef990c4b5e0890cc049e5 to your computer and use it in GitHub Desktop.
Fetch data with typed response from Zog schema
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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