GithubHelp home page GithubHelp logo

zaingz / use-axios-hooks Goto Github PK

View Code? Open in Web Editor NEW
28.0 2.0 4.0 3.99 MB

axios hooks for common network calls scenarios

Home Page: https://codesandbox.io/s/practical-sky-tpi6c

License: MIT License

HTML 4.99% JavaScript 91.82% CSS 3.19%
react-hooks api axios polling

use-axios-hooks's Introduction

use-axios-hooks

axios hooks for common network calls scenarios

npm version JavaScript Style Guide GitHub license Maintenance

Read here about my motivation for developing this library: https://medium.com/@zaingz/how-react-hooks-compares-to-redux-eba43788df46

Features

  • Simple and easy to use, no configuration needed.
  • Built on top of axios api.
  • Ability to retry if api call fails.
  • Ability to do api polling.
  • Ability to cancel in flight api calls.
  • Plays nicely with react component life cycle.

Installation

npm install --save axios use-axios-hooks

Axios is peerDependency of this lib so make sure you install axios separately.

Usage

import  React,  {  Component  }  from  'react'
import  { useAxios }  from  'use-axios-hooks'


const  Example  =  ()  =>  {
const  [{data, isLoading, error, isCanceled},  cancel] = useAxios('http://my-awesome-api/endpoint')

return (
  <div>
    {isLoading  &&  'Loading...'}
    {data && JSON.stringify(data)}
    {error && JSON.stringify(error)}
    <button onClick={() => cancel()}>cancel</button>
  </div>
)
}

Retry on error:

import  React,  {  Component  }  from  'react'
import  { useAxiosRetry }  from  'use-axios-hooks'


const  Example  =  ()  =>  {
const  [{data, isLoading, error, isCanceled},  cancel] = useAxiosRetry(
    "https://api-will-fail/retry",
    {
      retryCount: 2,
      retryInterval: 2000
    }
  );

return (
  <div>
    {isLoading  &&  'Loading...'}
    {data && JSON.stringify(data)}
    {error && JSON.stringify(error)}
    <button onClick={() => cancel()}>cancel retrying</button>
  </div>
)
}

Polling:

import  React,  {  Component  }  from  'react'
import  { useAxiosInterval }  from  'use-axios-hooks'


const  Example  =  ()  =>  {
const  [{data, isLoading, error, isCanceled},  cancel] = useAxiosInterval(
    "https://awesome-api/poll",
    4000
  );

return (
  <div>
    {isLoading  &&  'Loading...'}
    {data && JSON.stringify(data)}
    {error && JSON.stringify(error)}
    <button onClick={() => cancel()}>cancel polling</button>
  </div>
)
}

Edit practical-sky-tpi6c

API

useAxios(url | config)

Basic hook to make network calls.

Returns [{data, isLoading, error, isCanceled}, cancel]

  • data The response object returned by axios.
  • isLoading Boolean to indicate if request is started but not completed.
  • error Error object returned by axios.
  • isCancelled Boolean to indicate if request is canceled.
  • cancel Function to cancel pending network call. (It uses axios cancellation api).

useAxiosRetry(url | config, options)

Hook to retry network call on error.

  • url | config The request url or axios request config object.

  • options Configuration to specify retry options i.e { retryCount: number, retryInterval: milliseconds }

Returns [{data, isLoading, error, isCanceled}, cancel]

  • data The response object returned by axios.
  • isLoading Boolean to indicate if request is started but not completed.
  • error Error object returned by axios.
  • isCancelled Boolean to indicate if request is canceled.
  • cancel Function to cancel retying.

useAxiosInterval(url | config, interval)

Hook to do repeated network call after an interval (long polling).

  • url | config The request url or axios request config object.

  • interval Interval in milliseconds in which network will be made.

Returns [{data, isLoading, error, isCanceled}, cancel]

  • data The response object returned by axios.
  • isLoading Boolean to indicate if request is started but not completed.
  • error Error object returned by axios.
  • isCancelled Boolean to indicate if request is canceled.
  • cancel Function to cancel the polling.

License

MIT © zaingz


This hook is created using create-react-hook.

use-axios-hooks's People

Contributors

dependabot[bot] avatar zain-plutoflume avatar zaingz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

use-axios-hooks's Issues

Question: How can I use my axios client instance?

Hi, just a question.

Its possible to use it passing my axios instance? is just because i have authentication in a interceptor


const apiClient = axios.create({
  baseURL: '/.netlify/functions/',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
});

apiClient.interceptors.request.use(config => {
  const token = identity.currentUser()?.token?.access_token;
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.