/react-api-hooks

React hooks to interact with an API from a stateless component using axios.

Primary LanguageJavaScriptMIT LicenseMIT

React API Hooks

React hooks to interact with an API from a stateless component using axios.

Features:

  • Uses axios and allows for complete request control
  • Works with stateless/functional components
  • Ability to filter and paginate API results
  • Ability to delay API calls while the user is typing
  • Works with infinite scroll components
  • Request auto-cancellation for concurrent requests or component unmount

Examples:

Installation:

npm i react-api-hooks -s

Basic Usage:

import { useAPI } from 'react-api-hooks';

const TestComponent = () => {
  const { data=[], error, isLoading } = useAPI(url);
  
 if (error){
   return <Error />
 }
        
 if (isLoading){
   return <Loading />
 }
    
  return (
      <div>
        {data.map(item => <span key={item.id}>{item.text}</span>)}
      </div>
    )
}

Advanced Usage

import { useAPI } from 'react-api-hooks';

const TestComponent = () => {
  const axiosConfig = {
    method: 'POST',
    data: { foo: 'bar' },
    params: { id: '14' }
  };
  const { response, error, isLoading } = useAPI(url, axiosConfig);
  
 if (error){
   return <Error />
 }
        
 if (isLoading){
   return <Loading />
 }
    
  return (
      <div>
        {response.data.map(item => <span key={item.id}>{item.text}</span>)}
      </div>
    )
}

Reference: