This repository has been archived on 2023-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
react-rest-request/README.md

106 lines
2.1 KiB
Markdown
Raw Permalink Normal View History

# react-rest-request
2021-06-15 12:06:35 +03:00
Minimalist REST API client for React inspired by Apollo.
# Installation
```bash
npm install react-rest-request --save
```
# Usage
```typescript
import React from 'react';
import ReactDOM from 'react-dom';
import { Client, Endpoint, Method, useRequest, RequestProvider } from 'react-rest-request';
2020-11-05 22:16:19 +03:00
const client = new Client({
baseUrl: 'https://sampleapis.com/movies/api',
});
type Movie = Readonly<{
id: number;
title: string;
posterURL: string;
imdbId: string;
}>
const MoviesEndpoint: Endpoint<MoviesResponse, void> = {
method: Method.GET,
url: '/action-adventure',
};
type MoviesResponse = Movie[];
function App() {
const { data, loading } = useRequest(MoviesEndpoint);
return !data ? (
<div>{ loading ? 'Loading...' : 'Something went wrong' }</div>
) : (
<ul>
{data.map(movie => (
<li key={movie.id}>{movie.title}</li>
))}
</ul>
);
}
ReactDOM.render(
<RequestProvider client={client}>
<App />
</RequestProvider>,
document.getElementById('root'),
);
```
2020-12-23 05:33:28 +03:00
# Features
- [x] Automatic and lazy requests.
- [x] Transform response data.
- [x] Simple refetch of a previous request.
- [x] Automatic and manual cancellation of the request.
- [ ] Cache request responses.
### Transform response
If you have an endpoint that doesn't fit into your beautiful architecture
with its response data, you can transform the response before it's written
to the state.
```typescript
import { Endpoint, Method } from 'react-rest-request';
export type Movie = Readonly<{
id: number;
title: string;
posterURL: string;
imdbId: string;
}>
export const MoviesEndpoint: Endpoint<MoviesResponse, void> = {
method: Method.GET,
url: '/action-adventure',
transformResponseData(data: Movie[]) {
return {
items: data,
}
}
};
export type MoviesResponse = {
items: Movie[],
}
```
2020-11-20 23:48:38 +03:00
# License
Released under the [MIT License].
[MIT License]: https://github.com/pleshevskiy/react-rest-request/blob/master/LICENSE.md