@hesapkurdu/axios-helper
v2.0.0
Published
Developed for easy integration of progress spinner and error handler into axios.
Downloads
27
Readme
Axios Helper
Developed for easy integration of progress spinner and error handler into axios.
Installation
Use node package manager to install @hesapkurdu/axios-helper.
npm i @hesapkurdu/axios-helper
Basic Usage
// dataService.ts
// First parameter must be axios for all services.
const getData = (axios, ...otherParams) => {
return axios.get('url');
};
export default {
getData,
};
Initialize it in the root component.
// Root.tsx
import { AxiosProvider, OptionsOfServices } from '@hesapkurdu/axios-helper';
import dataService from './dataService';
import App from './App';
export const services = {
dataService,
};
const options: OptionsOfServices<keyof typeof services> = {
dataService: {
headers: { Authorization: 'token' },
isLoadingBlocked: false,
isErrorHandlerBlocked: false,
handleErrorsBy: 'status',
handleErrorsWith: { '404': 'not found' }, // format must be {[status]: 'error message'} and depends on the handleErrorsBy option
},
};
const errorHandler = (errorMessage) => {
// Globally handle error message in here.
// console.log(errorMessage);
// alert(errorMessage);
};
const Root = () => {
return (
<AxiosProvider services={services} options={options} errorHandler={errorHandler}>
<App />
</AxiosProvider>
);
};
export default Root;
Place your progress spinner in a suitable component.
// App.tsx
import { useContext } from 'react';
import { AxiosContext } from '@hesapkurdu/axios-helper';
import HomePage from './HomePage';
const ProgressSpinner = () => <p>Progress Spinner</p>;
const App = () => {
const { isLoading } = useContext(AxiosContext);
return (
<div>
<HomePage />
{isLoading && <ProgressSpinner />}
</div>
);
};
export default App;
Use axios everywhere.
// HomePage.tsx
import { useEffect } from 'react';
import { useAxios } from '@hesapkurdu/axios-helper';
import services from './Root.tsx';
const HomePage = () => {
// services can be imported with configured axios.
const {
services: { dataService },
} = useAxios<typeof services>();
useEffect(() => {
const getData = async () => {
try {
const { data } = dataService.getData();
} catch (error) {
if (!error?.config?.handled) {
// you can handle the errors that is not handled by the global error handler in here.
}
}
};
getData();
}, []);
return <p>Home Page</p>;
};
export default HomePage;