useAPIClient

Overview

Custom hook that simplifies API interactions using FETCH, which is built into react as standard

Tip

1. Add the custom hook and pass it into the function

Example : Default usage ( calling function )
import { useAPIClient } from '@ska-telescope/ska-login-page';

...

const authApiClient = useAPIClient();

...

const result = await <someFunction>(authApiClient, <optional options>);

2. Make use of the provided client within the function accessing the API

The called function, which will do the actual fetching will be something like the examples here

Example : Default usage ( processing function )
const someFunction = async (
   authApiClient: (url: string, options?: RequestInit) => Promise<Response>,
   inOptions?: any
) => {
   try {
      const headers = new Headers({});
      headers.append('Content-Type', `application/json`);

      const options = {
         method: 'POST',
         headers: headers,
         body: JSON.stringify(inOptions)
      };
      const response = await authApiClient(<full url>, options);
      const data: string = await response.json();
      return typeof response === 'undefined' ? 'error.API_UNKNOWN_ERROR' : data;
   } catch (e) {
      return e;
   }
};