react-axios-hook
🔥 A React Hook based on axios.
Features
- Using Axios with React Hook
- Support Typescript
- Support cancel request
- Global Config with
AxiosConfig
component - Flexible with config axios or axios instance
- FullControl with axios behavior,support loading status, manual refresh, fetching control...
Installation
npm install axios react-axios-hook
OR
yarn add axios react-axios-hook
axios
is a peer dependency and needs to be installed explicitly
Quick Start
Basic Usage
{ const response loading error refresh = if error return <div>JSON</div> return loading ? <div>Loading...</div> : <div>JSON</div>}ReactDOM
Global Config
{ const response loading error refresh = if error return <div>JSON</div> return loading ? <div>Loading...</div> : <div>JSON</div>} { return <AxiosConfig config=baseURL: 'https://www.mxnzp.com/api/'> <Demo /> </AxiosConfig> }ReactDOM
Documentation
API
API
The package exports one default export and a name export AxiosConfig:
import useAxios, { AxiosConfig } from 'react-axios-hook'
useAxios(url|config, options?, dependencies?)
The main React hook to execute HTTP requests.
url|config
- The request URL or config object, the same argument accepted byaxios
.options
- An options object.trigger
(true
) - If false, the request is not executed immediately. Useful for non-GET requests that should not be executed when the component renders.clear
(false
) - If true, new request will clear old response when request startcancelable
(false
) - If true, the last request will be canceled if last request is not finished when new request get into processing.initResponse
- If set, response will use this value as initial value
dependencies
- dependencies array
Returns:
[{ loading, error, response }, refresh]
-
loading
- True if the request is in progress, otherwise False. -
error
- The error value -
response
- The whole success response object. -
isCacel
- True if the request is canceled, otherwise False. -
refresh([url|config])
- A function to execute the request manually, bypassing the cache by default.url|config
- Same with useAxios's first parameter, which is shallow-merged with the config object provided when invoking the hook.
AxiosConfig
react-axios-hook
uses a default axios object unless you define your own by AxiosConfig
component.
This component will define a global axiosInstance for further use.
Attension: This is a React Component
Props
instance
- the customaxios
instance your defineconfig
- config object, the same argument accepted byaxios
, used to create a axios instanceoptions
- global optionstrigger
(true
)cancelable
(false
)clear
(false
)
When defining both instance
and config
, it will use instance
and ignore config
parameter.
Credits
react-axios-hook
is inspired by axios-hooks and swr
License
MIT