Request

A small wrapper around fetch with interceptors and abort support.

Request

import { Request } from '@cc-heart/utils-client'

const request = new Request('https://jsonplaceholder.typicode.com')

const { data, abort } = request.get<{ name: string }>('/users/1')
const user = await data // parsed JSON body

abort.abort() // cancel in-flight request
  • HTTP methods: get / post / put / delete
  • GET / DELETE bodies are serialized into the query string; POST / PUT bodies are sent as JSON
  • every call returns { data, abort } — abort is an AbortController

Interceptors

request.interceptor.requestInterceptor.push((config) => {
  // mutate request init before sending
  return config
})
request.interceptor.responseInterceptor.push((res) => res)
request.interceptor.errorInterceptor.push((err) => {
  console.error(err)
})

createFetchRequest

Curried helper that binds a Request instance into a one-call fetcher:

import { createFetchRequest } from '@cc-heart/utils-client'

const useFetch = createFetchRequest(new Request('https://api.example.com'))
const { data } = useFetch('/users/1', { method: 'GET' })

Demo

Fetch a user from JSONPlaceholder — pick an id and hit send:

Loading...