npm.io
1.0.1 • Published 5 years ago

@fabricefrancois/use-api

Licence
MIT
Version
1.0.1
Deps
0
Size
24 kB
Vulns
0
Weekly
0

use-api

React hook to manage API calls.

NPM JavaScript Style Guide

Getting Started

Prerequisites

This React hook relies on network requests being made using the axios library. Other http clients may be used as well as long as ok and data properties exist on the network response.

Install
npm install --save @fabricefrancois/use-api
Usage
import axios from axios;
import { useApi } from "@fabrice/use-api";
import React, { useEffect } from "react";

function App() {
  const api = useApi(axios.get, []);

  useEffect(() => {
    api.request('http://jsonplaceholder.typicode.com/users');
  }, []);

  return loading ? (
    <p>Loading users...</p>
  ) : (
    <>
      {api.data.map((user) => (
        <p key={user.id}>{user.name}</p>
      ))}
    </>
  );
}

API

Params

The useApi hook takes in two values

  • apiFunction - the network request to be made.

    function AddTodo(todo) {
      return axios.post("https://todos.com/add/", todo);
    }
  • initialState - the state before the request is made. By default, the initial state is an empty object.

Return Value

An object containing the following is returned from the hook:

  • data - the data returned from a successful network request (taken from the response's data property).
  • error - boolean value indicating whether the request was completed successfully. Similarly, this value is derived from the ok property on the response.
  • loading - boolean value indicating the status of the network request.
  • request - asynchronous function that sends the network request and handles the state. Any parameters are forwarded to the function passed into useApi. The original response is also returned from the function.

Example:

// the returned object can also be destructured to pick out individual properties
const { data, error, loading, request } = useApi(postTodo);

const todo = { title: "New Todo", status: "Not Done" };

// sending the request
const response = await request(todo, { setting1: 1, option2: 2});

License

MIT Fabricevladimir


This hook was created using create-react-hook.