Skip to main content
Version: v7.0.0

Quick Start

Hyper Fetch's core is framework-agnostic, requiring no external libraries to function.

What you'll learn
  • How to initialize the client
  • How to create requests
  • How to interact with the server

1. Initialize the Client

The first step is to initialize the Client. It manages the basic server connection configuration and all of Hyper Fetch's essential elements, such as dispatchers, cache, and app managers. Begin by specifying the url of your server.

client.ts
import { Client } from "@hyper-fetch/core";

export const client = new Client({ url: "http://localhost:3000" });

2. Create Requests

Once the client is set up, use its createRequest method to define requests and their associated types.

caution

We are using currying to achieve auto generated types for the endpoint string.
This solution will be removed once https://github.com/microsoft/TypeScript/issues/10571 get resolved.

requests.ts
import { client } from "../client.ts";

type ResponseType = { token: string; refreshToken: string };
type PayloadType = { email: string; password: string };

const login = client.createRequest<{
response: ResponseType;
payload: PayloadType;
}>()({
method: "POST",
endpoint: "/auth/login",
});

const getUsers = client.createRequest<{
response: User[];
queryParams?: { page?: number; limit?: number; search?: string };
}>()({
method: "GET",
endpoint: "/users",
});

3. Interact with server

Once you have your request instances, you can interact with the server. This can be done in two primary ways:

users.ts
import { getUsers } from "requests";

const fetchUsers = async () => {
const { data, error, status } = await getUsers.send();

if (data) {
// work with User[] data
// e.g., console.log(data);
} else {
// handle error
// e.g., console.error(error, status);
}
};
login.ts
import { login } from "requests";

const handleLogin = async (values: { email: string; password: string }) => {
const { data, error, status } = await login.send({ data: values });

if (data) {
// perform login
// e.g., store data.token
} else {
// handle error
// e.g., console.error(error, status);
}
};

That's it!

You've seen how straightforward it is to get started with Hyper Fetch.