Skip to content

A set of simple utilities for declarative async resource fetching.

License

Notifications You must be signed in to change notification settings

leancloud/use-resource

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

useResource

A set of simple utilities for declarative async resource fetching.

npm bundle size ci status code cov

Features

  • 🧾 Declarative, intuitive and minimal core API
  • ⚛ Atomic, composable enhancement hooks
  • 🔌 Protocol agnostic
  • 💪 Written in TypeScript
  • 🌲 Small size (~1KB gzipped) and tree-shaking ready

Install

npm install @leancloud/use-resource

Example

First, create a hook for fetch:

import { createResourceHook } from '@leancloud/use-resource';

async function fetchJSON<T>(...args: Parameters<typeof fetch>) {
  return (await (await fetch(...args)).json()) as T;
}

const useFetch = createResourceHook(fetchJSON);

use useFetch in the Clock component:

const Clock = () => {
  const [data, { error, loading, reload }] = useFetch<{ datetime: string }>([
    "https://worldtimeapi.org/api/timezone/etc/utc"
  ]);
  return (
    <div>
      <p>Current Time:</p>
      <p>
        {loading && "Loading..."}
        {error && error.message}
        {data && data.datetime}
      </p>
      <button onClick={reload}>Reload</button>
    </div>
  );
};

Edit use-resource-prototype

Advanced usage

Currently there is an introduction available in Chinese:

《用 React Hook 的风格加载数据》

🚧 We are working on the translation.

About

A set of simple utilities for declarative async resource fetching.

Topics

Resources

License

Stars

Watchers

Forks