@one-view/api-client

API client helper

Usage no npm install needed!

<script type="module">
  import oneViewApiClient from 'https://cdn.skypack.dev/@one-view/api-client';
</script>

README

@one-view/api-client

Installation

With NPM

$ npm install @one-view/api-client

With Yarn

$ yarn add @one-view/api-client

Usage

Fetch data in react component using useFetchData hook

import React from 'react'
import ReactDOM from 'react-dom'
import { ApiProvider, useFetchData } from '@one-view/api-client'

export App = () => {
  const { data, isLoading, error } = useFetchData('/endpoint')

  return (
    <div>
      {
        isLoading && <span>Fetching data...</span>
      }
      {
        error && <span>Error when fetching data</span>
      }
      {
        data && <span>{ data }</span>
      }
    </div>
  )
}

ReactDOM.render(
  <ApiProvider host="http://your-api-host">
    <App />
  </ApiProvider>,
  document.getElementById('container')
)

This example will fetch http://your-api-host/endpoint when App component is mounted.

Retry Request

By default the client will retry fetching 3 times. It is configurable in couple ways:

In ApiProvider

Adding retry prop in ApiProvider will affect all clients inside the component tree.

<ApiProvider host="..." retry={2}>
  <App />
</ApiProvider>

In useFetchData

useFetchData accept config object as second argument. This will override the config passed in ApiProvider.

const App = () => {
  const { data, isLoading, error } = useFetchData("/endpoint", {
    retry: 2,
    host: "http://other-api-host"
  });

  return <div>...</div>;
};

Watch for Prop Changes

const App = (props) => {
  // re-fetch data if props.code changes
  const result = useFetchData(`/endpoint/${props.code}`, {}, [ props.code ])

  return <div>...<div>;
}

Sending POST Request

useFetchData also return an axios instance under client name. You can use it to send POST or PATCH request.

const App = () => {
  return ({ client, data } = useFetchData("/endpoint"));
  const update = () => {
    return client.post("/update");
  };

  return <button onClick={update}>...</button>;
};

You can also use useClient hook if you don't need fetching any data. useClient accepts config object as parameter.

import { useClient } from "@one-view/api-client";

const App = () => {
  const client = useClient({ retry: 2 });
  const submit = () => {
    return client.post("/submit-form");
  };

  return <form onSubmit={submit}>...</form>;
};

Include Access Token in Request Header

You can add accessToken and tokenType (default to Bearer) to config object and the client will automatically include Authorization.

The recommended way to get the access token is by using useAccessToken hook from @one-view/auth-helpers package.

import { useFetchData } from "@one-view/api-client";
import { useAccessToken } from "@one-view/auth-helpers"

const App = () => {
  const token = useAccessToken();
  const client = useFetchData("/endpoint", {
    accessToken: token.accessToken,
    tokenType: token.tokenType
  });

  return <form onSubmit={submit}>...</form>;
};

Config Object

Name Type
host String
retry Number
accessToken String
tokenType String, default to Bearer

Typescript Integration

This package provides declaration files to use inside typescript project. For better experience, it is recommended to declare interface for the API response and pass it to useFetchData hook.

import { useFetchData } from '@one-view/api-client'

interface ApiResponse {
  id: number
  name: string
  ...
}

const App: React.FC = () => {
  // data will be properly typed and can be autocompleted
  const { data } = useFetchData<ApiResponse>('/endpoint')

  return <div>...</div>
}