2.0.0 • Published 2 years ago

@hesapkurdu/axios-helper v2.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

Axios Helper

Developed for easy integration of progress spinner and error handler into axios.

npm license size

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;
1.2.6

2 years ago

1.2.5

2 years ago

2.0.0

2 years ago

1.1.1

2 years ago

1.2.4

2 years ago

1.2.3

2 years ago

1.2.2

2 years ago

1.2.1

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago