@crushers-lab/axios-hooks
v0.0.3
Published
Axios wrapper for react
Downloads
20
Readme
Axios Hooks
Requirements
Requires
- React minimum 16.8.0
- Axios
- Prop Types
Install
npm i @crushers-lab/axios-hooks
OR
yarn add @crushers-lab/axios-hooks
Dependencies if not installed
npm i react axios prop-types
OR
yarn add react axios prop-types
Usage
Provide axios instance at root
import { AxiosProvider } from "@crushers-lab/axios-hooks";
import Axios from 'axios';
const connector = Axios.create();
function App() {
return (
<AxiosProvider connector={connector}>
...
<ExampleComponent />
</AxiosProvider>
)
}
Using hooks
import {useGet} from '@crushers-lab/axios-hooks';
function ExampleComponent() {
const [data, error, isLoading, status, reload ] = useGet('/user');
if(isLoading) {
return <div>Loading...</div>;
}
if(error) {
return <div>{error}</div>;
}
return <div>{data}</div>
}
Using Callback Methods
import {usePostCallback} from '@crushers-lab/axios-hooks';
function MyComponent() {
const postData = usePostCallback('/user');
const onSubmit = ()=>{
const data = {};
postData({data}).then(console.log).catch(console.error);
// Business logic
}
return <button onClick={onSubmit}>Submit</button>
}
Using Response Providers
import {AxiosGet, useAxiosData, useAxiosError} from "@crushers-lab/axios-hooks";
function MyComponent() {
return (
<AxiosGet url="/user" fallback={<div>Loading...</div>}>
<RenderUser />
</AxiosGet>
)
}
function RenderUser() {
const user = useAxiosData();
const error = useAxiosError();
if(error) {
return <div>{error}</div>;
}
return <div>{user.name}</div>
}