Quick Start
The basic version of Hyper Fetch is not associated with any framework or library that is required for it to work.
1. Initialize the Client
The first step in implementing Hyper Fetch is to initialize the Client. It
manages the basic configuration for connection to the server and all Hyper Fetch’s essential elements (i.e. instances of
dispatchers, cache, and app managers). Start by determining the url
of your server.
import { Client } from "@hyper-fetch/core";
export const client = new Client({ url: "http://localhost:3000" });
2. Create Requests
Then, having already prepared a connection to the server, we use the client method to create requests and assign types to them.
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.
import { client } from "../client.ts";
type ResponseType = { token: string; refreshToken: string };
type RequestType = { email: string; password: string };
const postLogin = client.createRequest<ResponseType, RequestType>()({ method: "POST", endpoint: "/auth/login" });
3. Use Requests
When you prepare request instances the next step is to use them. You can do it in two ways:
- React
- Typescript
import { useSubmit, useFetch } from "@hyper-fetch/react";
import { postUser, getUsers } from "server/auth";
// Submitting (mutation)
const { submit, submitting } = useSubmit(postUser.setData({ name: "John" }));
// Trigger submit
const { data } = await submit();
// Fetching
const { data, error, loading } = useFetch(getUsers);
import { postLogin } from "server/auth";
...
const handleLogin = async (values: {email: string, password: string}) => {
const { data, error, status } = await postLogin.send({data: values})
if(data) {
// perform login
...
} else {
// handle error
...
}
}
...