项目作者: pleshevskiy

项目描述 :
Minimalistic REST API client for React inspired by Apollo.
高级语言: TypeScript
项目地址: git://github.com/pleshevskiy/react-rest-request.git
创建时间: 2020-11-03T20:31:11Z
项目社区:https://github.com/pleshevskiy/react-rest-request

开源协议:MIT License

下载


react-rest-request

Minimalist REST API client for React inspired by Apollo.

Installation

  1. npm install react-rest-request --save

Usage

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import { Client, Endpoint, Method, useRequest, RequestProvider } from 'react-rest-request';
  4. const client = new Client({
  5. baseUrl: 'https://sampleapis.com/movies/api',
  6. });
  7. type Movie = Readonly<{
  8. id: number;
  9. title: string;
  10. posterURL: string;
  11. imdbId: string;
  12. }>
  13. const MoviesEndpoint: Endpoint<MoviesResponse, void> = {
  14. method: Method.GET,
  15. url: '/action-adventure',
  16. };
  17. type MoviesResponse = Movie[];
  18. function App() {
  19. const { data, loading } = useRequest(MoviesEndpoint);
  20. return !data ? (
  21. <div>{ loading ? 'Loading...' : 'Something went wrong' }</div>
  22. ) : (
  23. <ul>
  24. {data.map(movie => (
  25. <li key={movie.id}>{movie.title}</li>
  26. ))}
  27. </ul>
  28. );
  29. }
  30. ReactDOM.render(
  31. <RequestProvider client={client}>
  32. <App ></App>
  33. </RequestProvider>,
  34. document.getElementById('root'),
  35. );

Features

  • Automatic and lazy requests.
  • Transform response data.
  • Simple refetch of a previous request.
  • 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.

  1. import { Endpoint, Method } from 'react-rest-request';
  2. export type Movie = Readonly<{
  3. id: number;
  4. title: string;
  5. posterURL: string;
  6. imdbId: string;
  7. }>
  8. export const MoviesEndpoint: Endpoint<MoviesResponse, void> = {
  9. method: Method.GET,
  10. url: '/action-adventure',
  11. transformResponseData(data: Movie[]) {
  12. return {
  13. items: data,
  14. }
  15. }
  16. };
  17. export type MoviesResponse = {
  18. items: Movie[],
  19. }

License

Released under the MIT License.