Skip to content
Gravity Logo / Docs Gravity home
Browse documentation
Documentation/Gravity Web

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

paramdescriptionvalue
urlAPI endpoint URL to callurl string
methodHTTP methodstring default: GET
triggerBoolean to re-start the API calloptional

Example

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

const MyComponent = () => {

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

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