Giter VIP home page Giter VIP logo

use-api-call's Introduction

use-api-call

Minimal react hook to make api calls.

Installation

npm install use-api-call

yarn add use-api-call

Usage

// See examples on adavanced usage.

import React from "react";
import { useApiCall } from "use-api-call";

function App() {
  const { data, error, loading, invoke } = useApiCall(
    "https://api.github.com/users"
  );

  React.useEffect(() => {
    invoke(); // You don't have to call invoke() if you pass option {invokeOnMount: true} to useApiCall()'s second argument. But, isn't it nice to have control when you trigger ajax call.
  }, []);

  if (loading) return <p>Loading...</p>;

  return <div>{data}</div>;
}

API

  • useApiCall(request, [,options])

    • request - Function | URL string - Any function that returns Promise with data (or) A api url that returns JSON (uses fetch by default). (See the examples section).

      • Example: useApiCall(() => axios("/request/url/here").then(res => res.data))
    • options - Object - Options object.

    • returns an object with {data, error, loading, invoke} values. See the Returns section for details.

Options

  • updateOnlyIfMounted

    • Will update the data, error, loading values only if component is still mounted. Prevents "Can't perform a React state update on an unmounted component" warning.
    • Type: Boolean
    • Default: true
  • invokeOnMount

    • Runs ajax request when the component is mounted automatically. Basically, it does useEffect(() => { invoke(); }, []).
    • Type: Boolean
    • Default: false

Returns

  • data

    • Whatever is returned by your ajax call on success.
    • Type: any
    • Default: undefined
  • loading

    • A loader indicating whether request is running. You don't have to change anything here.
    • Type: Boolean
  • error

    • Error thrown by the request unmodified. i.e., Axios and fetch return different Error object structure, you'll have to check their documentation.
    • Type: Error
    • Default: undefined
  • invoke

    • A function which you'll call to run the ajax call. Invoke can take options that you normally send with your fetch or axios call. If you have passed your own function instead of passing URL string, You have to allow your function to take arguments. Please check the examples section to see how.
    • Type: Function

Examples

Check test/index.test.tsx for all different examples. I'll update some React examples soon.

// Manual invoke
const App = () => {
  const { data, error, invoke, loading } = useApiCall(() =>
    fetch("https://api.github.com/users").then((res: any) => res.json())
  );

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <button onClick={() => invoke()}>Click</button>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};
// Auto invoke on mount
const App = () => {
  const { data, error, invoke, loading } = useApiCall(
    () => fetch("https://api.github.com/users").then((res: any) => res.json()),
    {
      invokeOnMount: true,
    }
  );

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};
// Without ajax library. Uses fetch by default. You might have to polyfill for wide browser support.
const App = () => {
  const { data, error, invoke, loading } = useApiCall(
    "https://api.github.com/users",
    {
      invokeOnMount: true,
    }
  );

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};
// Pass arguments to axios.
const App = () => {
  const { data, error, invoke, loading } = useApiCall(
    (...args) => axios.get("https://api.github.com/users", ...args).then(res => res.data)
  );

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <button onClick={() => invoke({headers: {Authorization: "Bearer 12345xcxcxc"}})}>Get Users</button>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

use-api-call's People

Contributors

dependabot[bot] avatar saisandeepvaddi avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Forkers

meet-bhalodia

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.