0.0.3 • Published 4 years ago

@crushers-lab/axios-hooks v0.0.3

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

Axios Hooks

npm license size

Requirements

Requires

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>
}