Usage
Install
npm i axios @axios-use/react
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-instanceconst axiosInstance = axios.create({ baseURL: "https://example.com/",});ReactDOM.render( // custom instance <RequestProvider instance={axiosInstance}> <App /> </RequestProvider>, document.getElementById("root"));
RequestProvider config
config | type | explain |
---|---|---|
instance | object | axios instance |
cache | object | false | Customized cache collections. Or close. (Default on) |
cacheKey | function | Global custom formatted cache keys |
cacheFilter | function | Global callback function to decide whether to cache or not |
customCreateReqError | function | Custom format error data |
useRequest
option | type | explain |
---|---|---|
fn | function | get AxiosRequestConfig function |
options.onCompleted | function | This function is passed the query's result data. |
options.onError | function | This function is passed an |
options.instance | Customize the Axios instance of the current item |
// jsconst [createRequest, { hasPending, cancel }] = useRequest((id) => ({ url: `/user/${id}`, method: "DELETE",}));// tsxconst [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, onErrorconst [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 | get AxiosRequestConfig function |
parameters | array | false | |
options.cache | object | false | Customized cache collections. Or close |
options.cacheKey | string| number | function | Custom cache key value |
options.cacheFilter | function | Callback function to decide whether to cache or not |
options.filter | function | Request filter. if return a falsy value, will not start the request |
options.defaultState | object | Initialize the state value. |
options.onCompleted | function | This function is passed the query's result data. |
options.onError | function | This function is passed an |
options.instance | Customize the Axios instance of the current item |
// jsconst [{ data, error, isLoading }, fetch, refresh] = useResource((id) => ({ url: `/user/${id}`, method: "GET",}));// tsxconst [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 calledtype 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 parametersconst [reqState] = useResource( () => ({ url: "/users/", method: "GET", }), []);// conditionalconst [reqState, request] = useResource( (id) => ({ url: `/user/${id}`, method: "GET", }), [userId], { filter: (id) => id !== "12345", });request("12345"); // custom request is still useful// options: onCompleted, onErrorconst [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
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
const usersRes = await axios(api.getUsers());const userRes = await axios(api.getUserInfo("ID001"));
createRequestError
The
interface RequestError<T> { data?: T; message: string; code?: string | number; isCancel: boolean; original: AxiosError<T>;}