useAPI

The useAPI hook is designed to make API calls and handle errors gracefully. It returns the loading state and the fetched data.

const { data, loading } = useAPI(url, method, trigger);

The useAPI hook returns an object with two properties: loading and data. You can use the loading value to handle the loading state in the parent object. Data will be returned when the API response is returned.

The hook will automatically forward any errors to the error handler in the ViewContext.

Parameters

param

description

value

url

API endpoint URL to call

url string

method

HTTP method

string default: GET

trigger

Boolean to re-start the API call

optional

Example

import { useState } from 'react';
import { useAPI, Loader, Button } from 'components/lib';

const MyComponent = () => {

  const [trigger, setTrigger] = useState(false);
  const { data, loading } = useAPI('/user', 'GET', trigger);

  return (
    <div>
    
      { loading ? 
        <Loader/> : 
        <p>Data: { JSON.stringify(data) }</p> }
      
      <Button action={() => setTrigger(!trigger)}>
        Refresh Data
      </Button>
      
    </div>
  );
};

Last updated