react-axios-use-request
React hook for managing http requests with axios
Installation
You need to install axios too
yarn add react-axios-use-request axios
npm install react-axios-use-request axios --save
Usage
; const getPostComments = method: 'get' url: `https://jsonplaceholder.typicode.com/posts//comments`; const createPost = method: 'post' url: 'https://jsonplaceholder.typicode.com/posts' data: title: 'foo' body: 'bar' userId: 1 ; const getPostOptions = getRequestPayload: getPostComments cachePolicy: 'no-cache' ...responseData ...currentData initialData: {};const createPostOptions = getRequestPayload: createPost; { const loading error data doRequest reset abort updateData: updatePosts = ; const doRequest: apiCreatePost = ; if loading return ... if error return ... console; return <> <button type="button" onClick= { ; } > fetching </button> <button type="button" onClick= { ; } > create </button> <button type="button" onClick=abort> abort </button> <button type="button" onClick=reset> reset </button> </> }
Supported Options
name | type | defaultValue | required | description |
---|---|---|---|---|
getRequestPayload | function | null | v | A function return axios request config |
cachePolicy | string | no-cache | These will be the same ones as Apollo's fetch policies. Currently only supports no-cache or cache-and-network |
|
dataUpdater | function | (currentData, responseData) => responseData | Merges the current data with the response data | |
initialData | any | null | Set a default value for data | |
onAbort | function | empty function | Runs when the request is aborted | |
axiosInstance | function | original axios instance | You can create your own axios instance |
Notice
It is recommended that your options
object should be outside of component, remain same reference.
; const getPostComments = method: 'get' url: `https://jsonplaceholder.typicode.com/posts//comments`; const options = getRequestPayload: getPostComments; { const loading error data doRequest reset abort = ; ...}
Or you can use useMemo
to wrap your options and pass necessary props to dependency array
const options = ;
Supported API
name | description |
---|---|
loading | loading status |
error | error |
data | data |
doRequest | function that trigger request |
reset | function that reset data , loading , error |
abort | function that can abort request |
updateData | function that you can update data |
Notice
doRequest
will return Promise in the end, so if you want to do something after request success..
doRequest
、reset
、abort
、updateData
These functions identity are stable and won’t change on re-renders.
So you can safe to include or omit from the useEffect dependency list
;