Ecosyste.ms: Awesome

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

Awesome Lists | Featured Topics | Projects

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 1 month ago
JSON representation

Type to model asynchronous operations

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

npm 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