npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@signal-noise/use-api

v0.5.0

Published

A react hook to load data from a simple api.

Downloads

16

Readme

use-api

NPM version Actions Status PR Welcome

A simple react hook for loading data from an api with polling support.

Introduction

If you need a simple way to load data quickly this is for you. It allows you to very easily request data from any endpoint and have it available in your React application.

You can optionally specify a polling interval and manually trigger a refresh. It also gracefully cancels any open requests if you decide to change the URL and restarts timers if the polling interval changes.

const { data, loading, error, refresh } = useApi({
  url: "https://some-api.com/api",
  pollInterval: 10000,
  payload: { keywords: "hello" },
  method: "post",
  changed: (data) => console.log("The data changed!", data),
});

Installation

Install this package with npm.

npm i @signal-noise/use-api

Usage

Here is an example of a GET api call to retrieve a list of people which polls every 10 seconds, with a manual refresh button.

import React from 'react';
import useApi from '@signal-noise/use-api';
import PeopleList from './PeopleList';

const PeopleList = () = {
  const { data, loading, error, refresh } = useApi({
    url: "https://some-api.com",
    pollInterval: 10000
  });

  const people = data.people || [];

  return (
    <>
      {loading && <p>Loading...</p>}
      {error && <p>{error}</p>}
      <button onClick={refresh} disabled={loading}>Refresh</button>
      <PeopleList people={people} />
    </>
  );
}

You can optionally pass in data and specify the request type. Below is a minimal example of a user search UI. (You may wish to debounce the user input 🤷‍)

import React, { useState } from 'react';
import useApi from '@signal-noise/use-api';
import PeopleList from './PeopleList';

const PeopleSearch = () = {
  const [keywords, setKeywords] = useState("kazumi");

  const { data } = useApi({
    url: "https://some-api.com",
    payload: { keywords },
    method: "post"
  });

  const people = data.people || [];

  return (
    <>
      <input value={keywords} onChange={e=>setKeywords(e.target.value)} />
      <PeopleList people={data.people} />
    </>
  );
}

API

Input

  • url : Required - A URL to request data from.
  • pollInterval : Optional - How often to re-request updated data. Pass 0 to disable polling (the default behaviour).
  • payload : Optional - A data object to send with the request. If we are performing a GET request, it is appended into the querystring (e.g. ?keywords=hello). If it is a POST request it is sent in the request body as JSON.
  • headers : Optional - A data object containing http headers to send with the request. This must be a simple object with key value pairs like { authorization: "Bearer abc" }.
  • method : Optional - Set the request type, either get or post. (defaults to get)
  • changed : Optional - A function that is called if the data actually changed during the request. If this is specified, use-api does extra checking and compares old and new data. If data does not change, new data is not propagated and a redraw is saved. Please note, this may have performance repercussions if the data is large as it performs a deep comparison between new and old data to determine if they are equivalent.

Output

  • data: The data returned from the API.
  • loading: A boolean signifying if the data is currently being loaded.
  • error: A string representation of an error if it occurred during loading.
  • refresh: A function to call to re-request the data.

Note that a developer error, for example passing garbage as the method, will throw an exception. An issue within the API request itself will set an error within the response.