ReasonReact useFetch
npm install bs-use-fetchA ReasonReact useFetch hook. It:
- wraps bs-fetch
- is composable
- uses a result type
- makes impossible state irrepresentable
- lets you use a JSON decoding library of your choice
- lets you compose fetch errors and decoding error via polymorphic variants
It seems workable, especially for getting data, but expect some breaking
changes before v1.0.
``reasonFetchError(_)))
[@react.component]
let make = () => {
UseFetch.(
// fetch the data
useFetch(
"https://api.github.com/search/repositories?q=language:reason&sort=stars&order=desc",
)
// use whichever decoding library you like
->mapOk(r => GhRepo.t_decode(r)->Decode.mapDecodingError)
->(
// below, no distinction is made between fetching and refetching,
// but you're free to make other UX choices
fun
| Fetching => ReasonReact.string("Loading...")
| Refetching(Ok(({items}: GhRepo.t)))
| Complete(Ok(({items}: GhRepo.t))) =>
{Belt.Array.map(items, ({fullName, htmlUrl}: GhRepo.repo) =>
{ReasonReact.string(fullName)}
)
->React.array}
| Refetching(Error(
| Complete(Error(FetchError(_))) =>DecodeError((err: Decco.decodeError))))
{ReasonReact.string("Fetch error!")}
| Refetching(Error(
| Complete(Error(DecodeError((err: Decco.decodeError)))) =>`
{ReasonReact.string("Decode error!")}
);
};
(See the full example in /examples.)
Or, if you prefer the style prevalent in JS-land,
`reason
let (loading, data, error) = UseFetch.(
useFetch(
"https://api.github.com/search/repositories?q=language:reason&sort=stars&order=desc",
)
->mapOk(r => GhRepo.t_decode(r)->Decode.mapDecodingError)
->toLoadingDataAndError
);
// ...
`
See UseFetch.rei.
- [x] Add request/init parameters
- [ ] Support submitting
- [ ] toLoadingAndResult helperAbortController
- [ ] use (bs-fetch has a stale PR for same).rei` should already be
- [ ] tests (will probably require bindings for something like
jest-fetch-mock)
- [ ] Generate API docs (the comments in the
odoc-compatible.
- [ ] React Suspense compatibility?