An open API service indexing awesome lists of open source software.

https://github.com/leancloud/use-resource

A set of simple utilities for declarative async resource fetching.
https://github.com/leancloud/use-resource

fetch hook react request

Last synced: 6 months ago
JSON representation

A set of simple utilities for declarative async resource fetching.

Awesome Lists containing this project

README

          

# useResource

A set of simple utilities for declarative async resource fetching.

![npm](https://flat.badgen.net/npm/v/@leancloud/use-resource)
![bundle size](https://flat.badgen.net/bundlephobia/minzip/@leancloud/use-resource)
![ci status](https://img.shields.io/github/workflow/status/leancloud/use-resource/CI?style=flat-square)
![code cov](https://flat.badgen.net/codecov/c/github/leancloud/use-resource)

## 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

```bash
npm install @leancloud/use-resource
```

## Example

First, create a hook for `fetch`:
```tsx
import { createResourceHook } from '@leancloud/use-resource';

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

const useFetch = createResourceHook(fetchJSON);
```

use `useFetch` in the `Clock` component:

```tsx
const Clock = () => {
const [data, { error, loading, reload }] = useFetch<{ datetime: string }>([
"https://worldtimeapi.org/api/timezone/etc/utc"
]);
return (


Current Time:



{loading && "Loading..."}
{error && error.message}
{data && data.datetime}


Reload

);
};
```
[![Edit use-resource-prototype](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/use-resource-prototype-i5wys?fontsize=14&hidenavigation=1&theme=dark&view=preview)

## Advanced usage

Currently there is an introduction available in Chinese:

[ใ€Š็”จ React Hook ็š„้ฃŽๆ ผๅŠ ่ฝฝๆ•ฐๆฎใ€‹](https://www.notion.so/React-Hook-076214bf3d0d48b59220e9f702d9b879)

๐Ÿšง We are working on the translation.