JumboCode / TUTV

JumboCode project for TUTV, currently led by Frank Ma. Led by Deepanshu Utkarsh 2019 - 2020.
4 stars 0 forks source link

Add React hooks for connecting to the API #91

Closed controversial closed 4 years ago

controversial commented 4 years ago

This PR adds useApiData and useApiRequest hooks for easily requesting data from the API.

Note: this depends on #88; that PR should be merged before this one.

Usage

To fetch data to use in a component, simply use:

import { useApiData } from '../../api';

const MyComponent: React.FC = () => {
  const { data, error } = useApiData('api-route'); // 'data' and 'error' are either Objects or `undefined`; never promises or anything like that
  return (
    <div>
      { JSON.Stringify(data) }
    </div>
  );
}

The useApiData hook uses swr to implement caching, revalidation, and automatic retries.

To manually make API requests in a component without any of these features, use the useApiRequest hook instead.

import { useApiRequest } from '../../api';

const MyComponent: React.FC = () => {
  const sendReq = useApiRequest('api-route', { method: 'POST', body: 'hello' });
  return (
    <button type="button" onClick={sendReq}>
      click me
    </button>
  );
}

Details

Under the hood, it uses Zeit's swr library along with a fetch ponyfill.

Right now, there is no support for authentication, so all requests return the same JSON response:

{"detail":"Authentication credentials were not provided."}

A future (very soon) PR, which implements the client authentication flow, will update this useApi hook to automatically leverage API tokens added to the global application store.