@bjornagh/use-fetch

中文文档
0.0.12发布于 2019/09/28MITESM + CJS近 30 天下载 5603

An easy-to-use React hook for doing fetch requests

原始使用文档
文档目录10 节
  1. Features
  2. Install
  3. Usage
  4. API
  5. cachePolicy
  6. Examples
  7. POST request and update view afterwards
  8. Delay fetching using the lazy prop
  9. How to set base URL, default headers and so on
  10. Credits

@bjornagh/use-fetch

An easy-to-use React hook for doing fetch requests.

Features

  • 1️⃣ Dedupes requests done to the same endpoint. Only one request to the same endpoint will be initiated.
  • 💨 Caches responses to improve speed and reduce amount of requests.
  • 🛀 Automatically makes new requests if URL changes.
  • ⚛️ Small size, with only two dependencies: react and fetch-dedupe.

Install

npm install @bjornagh/use-fetch

# if yarn
yarn add @bjornagh/use-fetch

Usage

  1. Create a cache (new Map()) and render the FetchProvider at the top of your application.
import { FetchProvider } from "@bjornagh/use-fetch";

const cache = new Map();

ReactDOM.render(
  <FetchProvider cache={cache}>
    <App />
  </FetchProvider>,
  document.getElementById("container")
);
  1. Use useFetch in your component
import React from "react";
import { useFetch } from "@bjornagh/use-fetch";

function MyComponent() {
  const { data, fetching } = useFetch({
    url: "https://jsonplaceholder.typicode.com/todos"
  });

  return (
    <div>
      {fetching && "Loading..."}
      {data && data.map(x => <div key={x.id}>{x.title}</div>)}
    </div>
  );
}

See more examples in the examples section examples section .

API

useFetch accepts an object that supports the following properties

KeyDefault valueDescription
urlURL to send request to
methodGETHTTP method
lazynullLazy mode determines if a request should be done on mount and when the request parameters change (e.g. URL) or not. When null only GET requests are initiated when mounted and if for example the URL changes. If true this applies to all requests regardless of HTTP method. If false, requests are only initiated manually by calling doFetch, a function returned by useFetch
init{}See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch init argument for which keys are supported
dedupeOptions{}See https://github.com/jamesplease/fetch-dedupe#user-content-api dedupeOptions argument for which keys are supported
cacheResponsetrue if read request, false if writeCache response or not
requestKeynullrequestKey is used as cache key and to prevent duplicate requests. Generated automatically if nothing is passed.
cachePolicynullCaching strategy
refreshDoFetchFunctionBy default doFetch method is memoized (by useCallback) by using the request (url+method+body). Use this to override if you get a stale doFetch. It receives one argument, the default request key. e.g. requestKey => requestKey + 'something'
onErrorFunctionA callback function that is called anytime a fetch fails. Receives a Response as only argument. Logs to console by default
onSuccessFunctionA callback function that is called anytime a fetch succeeds. Receives a fetch Response as only argument. Does nothing by default (noop)

Return value

KeytypeDescription
responseResponseResponse
data*Request data response
fetchingBooleanWhether request is in-flight or not
errorResponseAny errors from fetch
requestKeyStringThe key used as cache key and to prevent duplicate requests
doFetchFunctionA function to initiate a request manually. Takes one argument: init, an object that is sent to fetch. See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch (init argument for which keys are supported). Returns a promise.

NOTE: Requests with Content-type set to application/json will automatically have their body stringified (JSON.stringify)

cachePolicy

  • cache-first - Uses response in cache if available. Makes request if not.
  • cache-and-network - Uses response in cache if available, but will also always make a new request in the background in order to refresh any stale data.
  • exact-cache-and-network - Similar to cache-and-network, but will only show cached response if the requests are identical (url+method+body).
  • network-only - Ignores cache and always makes a request.

Read requests (GET, OPTIONS, HEAD) default to cache-first.

Write requests (POST, DELETE, PUT, PATCH) default to network-only.

Examples

POST request and update view afterwards

function Demo() {
  // Fetch list of posts
  const posts = useFetch({
    url: "https://jsonplaceholder.typicode.com/posts"
  });

  // Prepare create request
  // This will not be initiated until you call `createPost.doFetch()`
  const createPost = useFetch({
    url: "https://jsonplaceholder.typicode.com/posts",
    method: "POST",
    init: {
      headers: {
        "Content-type": "application/json"
      }
    }
  });

  return (
    <div>
      <button
        onClick={() =>
          createPost
            .doFetch({
              body: {
                title: "foo",
                body: "bar",
                userId: 1
              }
            })
            .then(response => {
              if (response.ok) {
                // POST request was successful, refetch list of posts
                posts.doFetch();
              } else {
                // Do something with error response
              }
            })
        }
        disabled={createPost.fetching}
      >
        Create post
      </button>

      {!posts.data && posts.fetching && "Loading..."}
      {posts.data && posts.data.map(x => <h2 key={x.id}>{x.title}</h2>)}
    </div>
  );
}

Delay fetching using the lazy prop

Setting the lazy parameter to true tells useFetch to not start requesting on mount or when the request parameters change.

You can change this at any time. A common pattern where this feature is useful is when you want the user to apply some filters before you initiate a request.

Below is an example where a request is delayed until a search input contains at least two characters.

function LazyDemo() {
  const [searchFilter, setSearchFilter] = useState("");
  const posts = useFetch({
    url: `/posts?search=${searchFilter}`,
    lazy: searchFilter.length < 2 // Request is lazy as long as the input has less than two characters
  });

  return (
    <div>
      <input onChange={event => setSearchFilter(event.target.value)} />

      {posts.data && posts.data.map(x => <div key={x.id}>{x.title}</div>)}
    </div>
  );
}

How to set base URL, default headers and so on

Create your custom fetch hook. For example:

import { useFetch } from "@bjornagh/use-fetch";

function useCustomUseFetch({ url, init = {}, ...rest }) {
  // Prefix URL with API root
  const apiRoot = "https://my-api-url.com/";
  const finalUrl = `${apiRoot}${url}`;

  // Set a default header
  const finalHeaders = { ...init.headers };
  finalHeaders["Content-type"] = "application/json";

  // Ensure headers are sent to fetch
  init.headers = finalHeaders;

  return useFetch({ url: finalUrl, init, ...rest });
}

With a custom hook you could also set up a default error handler that show a toast message for example.

Credits

This library is heavily inspired by the excellent React library react-request

版本与发布记录

@bjornagh/use-fetch 共发布 12 个版本,首次发布于 2019/02/10;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.0.12latest2019/09/287 年前
0.0.112019/09/257 年前
0.0.102019/09/257 年前
0.0.92019/06/147 年前
0.0.82019/06/147 年前
0.0.72019/02/167 年前

关于 @bjornagh/use-fetch 的常见问题

@bjornagh/use-fetch 是什么?

An easy-to-use React hook for doing fetch requests

如何安装 @bjornagh/use-fetch?

在项目目录运行 npm install @bjornagh/use-fetch,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>= 16.8.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@bjornagh/use-fetch 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/bjornagh__use-fetch 是否存在。

@bjornagh/use-fetch 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@bjornagh/use-fetch 可以商用吗?

@bjornagh/use-fetch 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@bjornagh/use-fetch 的下载量有多少?

根据 npm 官方下载统计,@bjornagh/use-fetch 在 2026/10/08 – 2026/11/06 这 30 天内被下载 5,603 次,日均约 187 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bjornagh/use-fetch 还在维护吗?

最新版本 0.0.12 发布于 2019/09/28(7 年前);至今共发布 12 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/02/10。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。