Remote data type implemented in TS
npm install remote-data-ts
Type to model asynchronous operations data and the statuses it can be in.
Inspired by Elm's
krisajenkins/remotedata.
``
yarn add fp-ts remote-data-ts
npm i fp-ts remote-data-ts
`
Note fp-ts is a peer dependency.
RemoteData defines the statuses a fetched data can be:
`ts`
type RemoteData
`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 {body}
<>
{title}
>
);
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 (
render(
``
See other examples in examples/index.ts.
MIT ©
2022 Christian Gill