Skip to content

Latest commit

 

History

History
322 lines (266 loc) · 9.93 KB

README.zh-CN.md

File metadata and controls

322 lines (266 loc) · 9.93 KB

简体中文 | English


@axios-use/react - 一个 Axios 的 React Hook 插件,小而美 @axios-use/react - 一个 Axios 的 React Hook 插件,小而美
一个 Axios 的 React Hook 插件,小而美

NPM version NPM old version install size minzipped size ci license





使用

快速开始

import { useResource } from "@axios-use/react";

function Profile({ userId }) {
  const [{ data, error, isLoading }] = useResource((id) => ({ url: `/user/${id}` }), [userId]);

  if (error) return <div>failed to load</div>;
  if (isLoading) return <div>loading...</div>;
  return <div>hello {data.name}!</div>;
}
import { useRequest, useResource } from "@axios-use/react";

RequestProvider

import axios from "axios";
import { RequestProvider } from "@axios-use/react";

// custom Axios instance. https://github.com/axios/axios#creating-an-instance
const axiosInstance = axios.create({
  baseURL: "https://example.com/",
});

ReactDOM.render(
  // custom instance
  <RequestProvider instance={axiosInstance}>
    <App />
  </RequestProvider>,
  document.getElementById("root"),
);

RequestProvider 配置

config type explain
instance object 自定义 Provider 下的 Axios 实例
cache object | false 自定义 Provider 下的 Cache 对象,或关闭。 (默认开启)
cacheKey function 自定义 Provider 下的生成 Cache key 函数
cacheFilter function 缓存筛选器,自定义 Provider 下的过滤响应缓存,决定是否存储
customCreateReqError function 自定义 Provider 下的格式化错误响应

useRequest

option type explain
fn function 传递 Axios 请求配置的函数
options.onCompleted function 请求成功的回调函数
options.onError function 请求失败的回调函数
options.instance AxiosInstance 自定义当前项的 Axios 实例
// js
const [createRequest, { hasPending, cancel }] = useRequest((id) => ({
  url: `/user/${id}`,
  method: "DELETE",
}));

// tsx
const [createRequest, { hasPending, cancel }] = useRequest((id: string) =>
  // response.data: Result. AxiosResponse<Result>
  request<Result>({
    url: `/user/${id}`,
    method: "DELETE",
  }),
);
interface CreateRequest {
  // Promise function
  ready: () => Promise<[Payload<TRequest>, AxiosResponse]>;
  // Axios Canceler. clear current request.
  cancel: Canceler;
}

type HasPending = boolean;
// Axios Canceler. clear all pending requests(CancelTokenSource).
type Cancel = Canceler;
useEffect(() => {
  const { ready, cancel } = createRequest(id);

  ready()
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
      console.log(err);
    });
  return cancel;
}, [id]);
// options: onCompleted, onError
const [createRequest, { hasPending, cancel }] = useRequest(
  (id) => ({
    url: `/user/${id}`,
    method: "DELETE",
  }),
  {
    onCompleted: (data, response) => console.info(data, response),
    onError: (err) => console.info(err),
  },
);

useResource

option type explain
fn function 传递 Axios 请求配置的函数
parameters array | false 传递 Axios 配置函数参数的数组对象,effect 依赖项。false关闭依赖响应
options.cache object | false 自定义 Cache 对象,或关闭。 (默认继承全局)
options.cacheKey string| number | function 自定义生成 Cache key 函数
options.cacheFilter function 缓存筛选器,自定义过滤响应缓存,决定是否存储
options.filter function 请求筛选器,决定是否发起请求
options.defaultState object State 的初始化值. {data, response, error, isLoading}
options.onCompleted function 请求成功的回调函数
options.onError function 请求失败的回调函数
options.instance AxiosInstance 自定义当前项的 Axios 实例
// js
const [{ data, error, isLoading }, fetch, refresh] = useResource((id) => ({
  url: `/user/${id}`,
  method: "GET",
}));

// tsx
const [reqState, fetch, refresh] = useResource((id: string) =>
  // response.data: Result. AxiosResponse<Result>
  request<Result>({
    url: `/user/${id}`,
    method: "GET",
  }),
);
interface ReqState {
  // Result
  data?: Payload<TRequest>;
  // axios response
  response?: AxiosResponse;
  // normalized error
  error?: RequestError<Payload<TRequest>>;
  isLoading: boolean;
  cancel: Canceler;
}

// 不会调用 `options.filter` 函数
type Fetch = (...args: Parameters<TRequest>) => Canceler;

// 1. 与 `fetch` 函数类似, 但是没有传参, 保持使用 `useResource` 声明时传参
// 2. 会调用 `options.filter` 函数进行过滤操作
type Refresh = () => Canceler | undefined;

将其参数作为依赖项传递给 useResource,根据参数变化自动触发请求

const [userId, setUserId] = useState();

const [reqState] = useResource(
  (id) => ({
    url: `/user/${id}`,
    method: "GET",
  }),
  [userId],
);

// no parameters
const [reqState] = useResource(
  () => ({
    url: "/users/",
    method: "GET",
  }),
  [],
);

// conditional
const [reqState, request] = useResource(
  (id) => ({
    url: `/user/${id}`,
    method: "GET",
  }),
  [userId],
  {
    filter: (id) => id !== "12345",
  },
);

request("12345"); // custom request is still useful

// options: onCompleted, onError
const [reqState] = useResource(
  () => ({
    url: "/users/",
    method: "GET",
  }),
  [],
  {
    onCompleted: (data, response) => console.info(data, response),
    onError: (err) => console.info(err),
  },
);

cache

https://codesandbox.io/s/react-request-hook-cache-9o2hz

其他

request

request 作用于 Typescript 类型推导,便于识别 response 类型

const api = {
  getUsers: () => {
    return request<Users>({
      url: "/users",
      method: "GET",
    });
  },

  getUserInfo: (userId: string) => {
    return request<UserInfo>({
      url: `/users/${userId}`,
      method: "GET",
    });
  },
};

当然你也可以直接使用 axios 调用 request 方法

const usersRes = await axios(api.getUsers());

const userRes = await axios(api.getUserInfo("ID001"));

自定义 response 类型. (如果你有手动修改 response 数据的需求。 axios.interceptors.response)

import { request, _request } from "@axios-use/react";
const [reqState] = useResource(() => request<DataType>({ url: `/users` }), []);
// AxiosResponse<DataType>
reqState.response;
// DataType
reqState.data;

// 自定义 response 类型
const [reqState] = useResource(() => _request<MyWrapper<DataType>>({ url: `/users` }), []);
// MyWrapper<DataType>
reqState.response;
// MyWrapper<DataType>["data"]. maybe `undefined` type.
reqState.data;

createRequestError

createRequestError 用于规范错误响应(该函数也默认在内部调用)。 isCancel 标志被返回,因此也不必在 promise catch 块上调用 axios.isCancel

interface RequestError<T> {
  data?: T;
  message: string;
  code?: string | number;
  isCancel: boolean;
  original: AxiosError<T>;
}

许可证

MIT