Skip to content

This is a demo project that showcases how to use the Untypeable library with Wretch to make API requests to JsonPlaceholder and display the data on a webpage.

License

Notifications You must be signed in to change notification settings

jellydn/untypeable-wretch-demo

Repository files navigation

Welcome to untypeable-wretch-demo πŸ‘‹

Version

🏠 Homepage

✨ Demo

IT Man - Tip #35 - How to use #untypeable generate type-safe API clients [Vietnamese]

In this demo project, we demonstrate how to use Untypeable in conjunction with the Wretch library to make API requests to JsonPlaceholder and display the retrieved data on a webpage.

https://gyazo.com/7c47e1e4e0fb1851f737c33d0bb09b6b.gif

Why Untypeable

One of the key benefits of Untypeable is that it provides a zero-bundle size option. This means that you can use Untypeable to generate type-safe API clients without adding any additional bundle size to your application. This can help to improve the performance and load times of your application.

import { createTypeLevelClient, initUntypeable } from "untypeable";
import wretch from "wretch";

const u = initUntypeable();

export type Post = {
  id: number;
  title: string;
  body: string;
  userId: number;
};

// Create a router
const fetcherRouter = u.router({
  "/posts": u
    .input<{
      userId?: number;
    }>()
    .output<Post[]>(),
});

const BASE_URL = "https://jsonplaceholder.typicode.com";

const externalApi = wretch(BASE_URL, { mode: "cors" }).errorType("json");

export const fetcher = createTypeLevelClient<typeof fetcherRouter>(
  async (path, input) => {
    const res = externalApi.get(`${path}?${new URLSearchParams(input)}`);
    return res.json();
  }
);
Screen.Recording.2023-04-16.at.2.04.46.PM.mov

Why Wretch

Write something like this

wretch("anything")
  .get()
  .notFound(error => { /* ... */ })
  .unauthorized(error => { /* ... */ })
  .error(418, error => { /* ... */ })
  .res(response => /* ... */)
  .catch(error => { /* uncaught errors */ })

instead of

fetch("anything")
  .then(response => {
    if(!response.ok) {
      if(response.status === 404) throw new Error("Not found")
      else if(response.status === 401) throw new Error("Unauthorized")
      else if(response.status === 418) throw new Error("I'm a teapot !")
      else throw new Error("Other error")
    }
    else // ...
  })
  .then(data => /* ... */)
  .catch(error => { /* ... */ })

Pretty neat,right? 😍

Built with

Install

yarn install

Usage

yarn dev

Author

Show your support

kofi paypal buymeacoffee

Give a ⭐️ if this project helped you!

About

This is a demo project that showcases how to use the Untypeable library with Wretch to make API requests to JsonPlaceholder and display the data on a webpage.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published