1.0.0 • Published 5 years ago

react-fetchable v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

react-fetchable

Data fetching in React the functional way powered by TypeScript, io-ts & fp-ts

What is this?

This small library uses the encoding and decoding capabilities of io-ts and the algebraic data types of [fp-ts[(https://github.com/gcanti/fp-ts) to provide developers with a type-safe and declarative data fetching API for React applications:

<Fetchable
  url="/data/schedule.json"
  validator={ActivityArrayValidator}
  loading={() => <div>Loading...</div>}
  error={(e: Error) => <div>Error: {e.message}</div>}
  success={(data: IActivityArray) => {
    return (
      <Table
        headers={["Time", "Activity"]}
        rows={data.map(a => [`${a.startTime}`, a.title])}
      />
    );
  }}
/>

Motivation

Loading data in React it is a very repetitive and tedious task. If that wasn't bad enough, the data contained in an HTTP response could be completely different from what we are expecting.

The type-unsafe nature of fetch calls is particularly dangerous for TypeScript users because it compromises many of the benefits of TypeScript.

Installation

You can install this module using npm:

npm install io-ts fp-ts react-fetchable

You can then import it as follows:

import { Fetchable } from "react-fetchable";

Options

PropDescription
urlThe URI of the resource to be loaded
validatorA value of the io-ts type Type<A, O, I>
loadingProvides the JSX to be rendered while the resource is loading.
errorProvides the JSX to be rendered if the data loaded and validated incorrectly.
successProvides the JSX to be rendered if the data loaded and validated correctly.
initAn instance of RequestInit that can be used to configure the fetch call.