🚀 Axios in React in the hooks era
npm i axios use-axios-react
Features
- Hooks for ✅ data fetching ✅ CRUD ✅ Batch operations
- ✅ Request cancellation
- ✅ Retry/reload callbacks
- ✅ Zero-configuration, yet fully configurable when needed
- ✅ No app architecture commitments, drop in into your React and Axios project and start using hooks in your new components
- No extra-dependencies (React and Axios are peer dependencies), thus minimum overhead if your project already uses axios
- All axios features
Installation
npm i use-axios-react
Make sure axios itself is installed
npm i axios
And make sure you use React v16.8.0 or newer.
Examples
Basic data fetching (GET)
;; const KanyeQuote = { const data loading = ; if loading return <div>Loading...</div>; return <blockquote>dataquote</blockquote>;};
Cancellable fetching (GET) with reload and retry
;; const KanyeQuote = { const data loading error retry = ; if loading return <Spinner />; if error return <Button onClick=retry label="RETRY" />; return <div> <Quote>dataquote</Quote> <Button onClick=retry label="RELOAD" /> </Fragment> ;};
Basic POST example
;; { return url: "https://reqres.in/api/users" data: name job ;} const CreateUser = { const create sending error data = ; const neo = name: "Neo" job: "The One" ; const morpheus = name: "Morpheus" job: "Leader" ; return <Layout> <Button onClick= >Neo</Button> <Button onClick= >Morpheus</Button> <StatusBar sending=sending error=error lastUser=data /> </Layout> ;};
Pagination
;; const PaginatedKanyeQuotes = { const page setPage = ; const data loading = ; if loading return <Spinner />; const prev = ; const next = ; return <div> <Quote>dataquote</Quote> <div> <Button onClick=prev disabled=page <= 1 label="← Prev" /> <span className="mx-5">Page page</span> <Button onClick=next disabled=page >= 9 label="Next →" /> </div> </div> ;};
Basic TodoMVC CRUD
;;; ; /** * Map todos to axios request configs */const todoObjectToAxiosRequest = url: id ? `/todos/` : "/todos" data: title order completed ; const TodoMvcApp = { // Reusing the same mapping function for all CRUD requests const create creating error: createError = ; const remove removing error: removeError = ; const update updating error: updateError = ; // Re-fetch after any of actions is completed const allRequestsDone = !creating && !removing && !updating; const todos = fetching error: fetchError = ; if createError || removeError || updateError || fetchError return <div>Error occurred please reload</div>; return <Layout> <Header loading=creating || removing || updating || fetching> <NewTodo create=create /> </Header> <TodoList todos=todos remove=remove update=update loading=fetching /> </Layout> ;};
Common state GET & POST
;; const CreateUser = { // Do an initial load const users = loading error: loadError setData: setUsers = ; // We're particularly interested in the create() callback and the response data (new user data) const create creating error: createError data: newUser = ; // Update users state evey time the newUser changes ; return <Layout> <Button onClick= >Create dummy user</Button> <span>loading || creating && "Loading..."</span> <span>loadError || createError && "Error occurred"</span> <UserList users=users /> </Layout> ;};
Example apps
API Overview
Hooks
useGetData() |
Use this one if you need to fetch data depending on some state (e.g. to fetch search results depending on search term) |
usePostCallback() usePutCallback() usePatchCallback() useDeleteCallback() useGetCallback() |
Use this if you need to create callbacks to trigger a request programmatically |
useParallelPostCallback() useParallelPutCallback() useParallelPatchCallback() useParallelDeleteCallback() useParallelGetCallback() |
Use this if you need to create callbacks to trigger batch requests |
Settings
provideAxiosInstance() |
Provide a custom axios instance to use with the hooks |
API Reference
useGetData(url|axiosConfig, options): []
url|axiosConfig
— Refer to axios request config documentation for detailsoptions
— Theuse{...}Data
hook options:
cancelable: bool |
Whether the request should be canceled on component unmount |
depends: [] |
Hook's effect will be re-run only if one of the passed array values changes. Refer to the React useEffect(effect, depends) second argument docs to learn how it works. |
willRun: bool |
Request will be be executed only if this option is true. This is usually an expression such as willRun: !loading |
- result array structure is
[data, loading, { error, response, retry, retriesCount, setData }]
:
use{Method}Callback(url|axiosConfig|factory, options): []
Where {Method} is one of the following: Post, Put, Patch, Delete, Get
url|axiosConfig|factory
— Request URL, axios config object or factory, producing an axios config object from callback args
- result array structure is
[exec, loading, { error, retry, response, data, execCount, input }]
:
useParallel{Method}Callback(axiosConfigFactory): []
Where {Method} is one of the following: Post, Put, Patch, Delete, Get
axiosConfigFactory
— A function producing an axios config object from callback args
- result array structure is
[exec, loading, { retry, errors, responses, data, succeed, failed, execCount, input }]
Support 👩
- Please feel free to create issues with questions