6.6.0 • Published 1 year ago

@axios-use/react v6.6.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

English | 简体中文

Usage

Quick Start

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

configtypedefaultexplain
instanceobjectaxiosaxios instance
cacheobject | false_ttlcacheCustomized cache collections. Or close. (Default on)
cacheKeyfunctiondefaultCacheKeyGeneratorGlobal custom formatted cache keys
cacheFilterfunction-Global callback function to decide whether to cache or not
customCreateReqErrorfunction-Custom format error data
getResponseItemfunction(r) => r.datacustom data value. The default value is response'data'.

useRequest

optiontypeexplain
fnfunctionget AxiosRequestConfig function
options.onCompletedfunctionThis function is passed the query's result data.
options.onErrorfunctionThis function is passed an RequestError object
options.instanceAxiosInstanceCustomize the Axios instance of the current item
// 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

optiontypeexplain
fnfunctionget AxiosRequestConfig function
parametersarray | falsefn function parameters. effect dependency list
options.cacheobject | falseCustomized cache collections. Or close
options.cacheKeystring| number | functionCustom cache key value
options.cacheFilterfunctionCallback function to decide whether to cache or not
options.filterfunctionRequest filter. if return a falsy value, will not start the request
options.defaultStateobjectInitialize the state value. {data, response, error, isLoading}
options.onCompletedfunctionThis function is passed the query's result data.
options.onErrorfunctionThis function is passed an RequestError object
options.instanceAxiosInstanceCustomize the Axios instance of the current item
// 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` will not be called
type Fetch = (...args: Parameters<TRequest>) => Canceler;

// 1. Same as `fetch`. But no parameters required. Inherit `useResource` parameters
// 2. Will call `options.filter`
type Refresh = () => Canceler | undefined;

The request can also be triggered passing its arguments as dependencies to the useResource hook.

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

other

request

The request function allows you to define the response type coming from it. It also helps with creating a good pattern on defining your API calls and the expected results. It's just an identity function that accepts the request config and returns it. Both useRequest and useResource extract the expected and annotated type definition and resolve it on the response.data field.

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

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

You can also use these request functions directly in axios.

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

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

custom response type. (if you change the response's return value. like axios.interceptors.response)

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

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

createRequestError

The createRequestError normalizes the error response. This function is used internally as well. The isCancel flag is returned, so you don't have to call axios.isCancel later on the promise catch block.

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

License

MIT

6.6.0

1 year ago

6.5.0

2 years ago

6.4.1

2 years ago

6.4.2

2 years ago

6.4.0-alpha.0

2 years ago

6.4.0

2 years ago

6.3.0

3 years ago

6.2.1-alpha.1

3 years ago

6.2.0-alpha.1

3 years ago

6.2.0

3 years ago

6.1.0

3 years ago

6.0.0

3 years ago

6.0.0-alpha.1

3 years ago