Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/gillchristian/remote-data-ts
Type to model asynchronous operations
https://github.com/gillchristian/remote-data-ts
remote-data types typescript
Last synced: about 2 months ago
JSON representation
Type to model asynchronous operations
- Host: GitHub
- URL: https://github.com/gillchristian/remote-data-ts
- Owner: gillchristian
- License: mit
- Created: 2018-12-20T21:34:10.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2023-06-13T16:18:25.000Z (over 1 year ago)
- Last Synced: 2024-10-12T22:56:05.538Z (2 months ago)
- Topics: remote-data, types, typescript
- Language: TypeScript
- Homepage: https://gillchristian.github.io/remote-data-ts
- Size: 389 KB
- Stars: 19
- Watchers: 1
- Forks: 1
- Open Issues: 3
-
Metadata Files:
- Readme: readme.md
- License: LICENSE.md
Awesome Lists containing this project
README
remote-data-ts
[![Test](https://github.com/gillchristian/remote-data-ts/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/gillchristian/remote-data-ts/actions/workflows/build.yml)
Type to model asynchronous operations data and the statuses it can be in.
Inspired by Elm's
[krisajenkins/remotedata](https://package.elm-lang.org/packages/krisajenkins/remotedata/latest/RemoteData).## Install
```
yarn add fp-ts remote-data-tsnpm i fp-ts remote-data-ts
```Note `fp-ts` is a peer dependency.
## Usage
RemoteData defines the statuses a fetched data can be:
```ts
type RemoteData = NotAsked | Loading | Success | Failure;
``````tsx
import React, { useState, useEffect, SFC } from 'react';
import { render } from 'react-dom';
import { pipe } from 'fp-ts/function';
import * as RD from 'remote-data-ts';import './styles.css';
interface ArticleProps {
title: string;
body: string;
}const Article: SFC = ({ title, body }) => (
<>
{title}
{body}
>
);type State = RD.RemoteData;
const App: SFC = () => {
const [state, setState] = useState(RD.notAsked);useEffect(() => {
setState(RD.loading);fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((res) =>
res.ok ? res.json() : new Error(`${res.status} ${res.statusText}`),
)
.then((article: ArticleProps) => {
setState(RD.success(article));
})
.catch((err: Error) => {
setState(RD.failure(err.message));
});
}, []);return (
{pipe(
state,
RD.match({
notAsked: () => null,
loading: () =>... loading ...,
success: (article) => ,
error: (msg) => (
Failed to load article: {msg}
),
}),
)}
);
};render(, document.getElementById('root'));
```See other examples in [examples/index.ts](/examples/index.ts).
## License
[MIT](https://github.com/gillchristian/remote-data-ts/blob/master/LICENSE) ©
2022 Christian Gill