sachasi / nextkit-fetcher

πŸš™ A simple, type-safe fetcher for nextkit

Home Page:https://nextkit-fetcher.js.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

nextkit-fetcher

XO code style

A simple and type-safe fetcher for nextkit.

Installation βˆ™ npm

# npm
npm install nextkit-fetcher

# yarn
yarn add nextkit-fetcher

# pnpm
pnpm add nextkit-fetcher

Usage

Use it on the frontend while fetching your own Endpoints.

import useSWR from "swr";
import { fetcher } from "nextkit-fetcher";

const Index: NextPage<Props> = (props) => {
  const { data } = useSWR("/api/user", fetcher);

  return <p>Hello {data.name}!</p>;
};

If it fails it wil throw a NextkitClientError.

Check the full API on πŸ“–

https://nextkit-fetcher.js.org

Extra

If you are not a fan of adding dependencies, copy-paste this πŸ‘‡

import { NextkitClientError } from "nextkit/client";

import type { APIResponse } from "nextkit";

export async function fetcher<T>(url: string, options?: RequestInit) {
  const request = await fetch(url, options);

  if (request.status >= 400) {
    throw new NextkitClientError(request.status, "Error While Fetching");
  }

  const body = (await request.json()) as APIResponse<T>;

  if (!body.success) {
    throw new NextkitClientError(request.status, body.message);
  }

  return body.data;
}

Support

Open an Issue, I will check it a soon as possible πŸ‘€

If you want to hurry me up a bit send me a tweet πŸ˜†

Consider supporting me on Patreon if you like my work πŸš€

Don't forget to start the repo ⭐

Licence

Licensed under the MIT License.

About

πŸš™ A simple, type-safe fetcher for nextkit

https://nextkit-fetcher.js.org

License:MIT License


Languages

Language:TypeScript 100.0%