Skip to content

Commit 9a8a53f

Browse files
authored
Merge pull request #28 from vannozzi/readme
readme hooks and events sections
2 parents 9a8b071 + 7817564 commit 9a8a53f

File tree

4 files changed

+118
-7
lines changed

4 files changed

+118
-7
lines changed

README.md

Lines changed: 113 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<h1 align="center">React http fetch</h1>
22

33
<p align="center">
4-
<img src="assets/img/react-http-fetch-logo.png" alt="react-http-fetch logo" width="120px" height="120px"/>
4+
<img src="assets/img/react-http-fetch-logo.png" alt="react-http-fetch logo"/>
55
<br>
66
<i>A http library for React JS built on top of JS native fetch.</i>
77
<br>
@@ -44,6 +44,12 @@ Just follow links below to get an overview of library features.
4444
- [Example &ndash; Abortable request](#example--abortable-request)
4545
- [Example &ndash; Get request](#example--get-request)
4646
- [Request hooks](#request-hooks)
47+
- [Http request hook params](#http-request-hook-params)
48+
- [Http request hook return](#http-request-hook-return)
49+
- [Http request state](#http-request-state)
50+
- [Example &ndash; Http request hook triggered automatically on component mount](#example--http-request-hook-triggered-automatically-on-component-mount)
51+
- [Example &ndash; Http request hook triggered manually on component mount](#example--http-request-hook-triggered-manually-on-component-mount)
52+
- [Example &ndash; Http post request hook](#example--http-post-request-hook)
4753
- [Events](#events)
4854
- [Caching](#caching)
4955
- [Browser support](#browser-support)
@@ -65,7 +71,7 @@ yarn add react-http-fetch
6571
```
6672

6773
## Provider
68-
You can override the default configuration used by the http client to peform any request by using the `HttpClientConfigProvider`:
74+
You can override the default configuration used by the http client to perform any request by using the `HttpClientConfigProvider`:
6975

7076
```js
7177
import { defaultHttpReqConfig, HttpClientConfigProvider } from 'react-http-fetch';
@@ -279,10 +285,115 @@ export default App;
279285
<br>
280286

281287
## Request hooks
288+
The library provides a hook `useHttpRequest` managing the state of the http request. Such state is returned by the hook along with a function to trigger the request. See [params](#http-request-hook-params) and [return](#http-request-hook-return) for more info. A dedicated hook is provided for every http method: `useHttpGet`, `useHttpPost`, `useHttpPatch`, `useHttpPut`, `useHttpDelete`.
289+
290+
### Http request hook params
291+
| Parameter | Type | Description |
292+
| --------- | ---- | ----------- |
293+
| baseUrlOverride | string | The base url of the request. If provided, it would override the [provider](#provider) base url.
294+
| relativeUrl | string | The url relative to the base one (e.g. posts/1).
295+
| parser | [HttpResponseParser](src/client/types.ts) | An optional response parser that would override the [provider](#provider) global one. |
296+
| requestOptions | [HttpRequestOptions](./src/client/types.ts) | The options carried by the fetch request. |
297+
| initialData | any | The value that the state assumes initially before the request is send. |
298+
| fetchOnBootstrap | boolean | Tell if the fetch must be triggered automatically when mounting the component or not. In the second case we would like to have a manual fetch, this is optained by a request function returned by the hook. |
299+
300+
### Http request hook return
301+
Returns an array of two elements, the first one embeds the state of the http request and the second one is a function that can be used to trigger the http request. The table below describes the shape (i.e. properties) of http request state.
302+
303+
### Http request state
304+
| Property | Type | Description |
305+
| --------- | ---- | ----------- |
306+
| pristine | boolean | Tells if the request has been dispatched. |
307+
| errored | boolean | Tells if the request has returned an error. |
308+
| isLoading | boolean | Tells if the request is pending. |
309+
| error | unknown | property evaluated by the error generated by the backend api. |
310+
| data | any | The response provided by the backend api. |
311+
312+
### Example &ndash; Http request hook triggered automatically on component mount
313+
```js
314+
import { useHttpRequest } from 'react-http-fetch';
315+
316+
function App() {
317+
const [state] = useHttpRequest({
318+
baseUrlOverride: 'https://jsonplaceholder.typicode.com',
319+
relativeUrl: 'todos/1',
320+
requestOptions: {},
321+
initialData: {},
322+
fetchOnBootstrap: true,
323+
});
324+
325+
return (
326+
<div>{`Todo name: ${state && state.data && state.data.title}`}</div>
327+
);
328+
}
329+
330+
export default App;
331+
```
332+
333+
<br>
334+
335+
### Example &ndash; Http request hook triggered manually on component mount
336+
```js
337+
import { useHttpRequest } from 'react-http-fetch';
338+
import { useEffect } from 'react';
339+
340+
function App() {
341+
const [state, request] = useHttpRequest({
342+
baseUrlOverride: 'https://jsonplaceholder.typicode.com',
343+
relativeUrl: 'todos/1',
344+
});
345+
346+
useEffect(() => request(), [request]);
347+
348+
return (
349+
<div>{`Todo name: ${state && state.data && state.data.title}`}</div>
350+
);
351+
}
352+
353+
export default App;
354+
```
355+
356+
### Example &ndash; Http post request hook
282357

283358
<br>
284359

285360
## Events
361+
Every time a request is executed the events shown below will be emitted. Each event carries a specific payload.
362+
363+
| Event type | Payload type |
364+
| --------- | ---- |
365+
| [RequestStartedEvent](src/events-manager/events/request-started-event.ts) | [HttpRequest](src/client/http-request.ts) |
366+
| [RequestErroredEvent](src/events-manager/events/request-errored-event.ts) | [HttpError](src/errors/http-error.ts) |
367+
| [RequestSuccededEvent](src/events-manager/events/request-succeded-event.ts) |[RequestSuccededEventPayload](src/events-manager/events/request-succeded-event.ts) |
368+
369+
It's possible to subscribe a specific event using the [useHttpEvent](src/events-manager/use-http-event.ts) hook as shown below:
370+
371+
```js
372+
import { useState } from 'react';
373+
import { RequestErroredEvent, RequestStartedEvent, RequestSuccededEvent, useHttpEvent, useHttpRequest } from 'react-http-fetch';
374+
375+
function App() {
376+
const [count, setCount] = useState(0);
377+
378+
const [, request] = useHttpRequest({
379+
baseUrlOverride: 'https://jsonplaceholder.typicode.com',
380+
relativeUrl: 'todos/1',
381+
});
382+
383+
useHttpEvent(RequestStartedEvent, () => setCount(count + 1));
384+
useHttpEvent(RequestSuccededEvent, () => setCount(count > 0 ? count - 1 : 0));
385+
useHttpEvent(RequestErroredEvent, () => setCount(count > 0 ? count - 1 : 0));
386+
387+
return (
388+
<>
389+
<button onClick={request}>{'increment count:'}</button>
390+
<span>{count}</span>
391+
</>
392+
);
393+
}
394+
395+
export default App;
396+
```
286397

287398
<br>
288399

17.5 KB
Loading

src/events-manager/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
export * from './event-bus';
22
export * from './event-bus-context';
33
export * from './types';
4-
export * from './use-bus-subscribe';
4+
export * from './use-http-event';
55
export * from './events';

src/events-manager/use-bus-subscribe.ts renamed to src/events-manager/use-http-event.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ import { HttpEventClassType, HttpEventHandler } from './types';
44
import { useEventBus } from './event-bus-context';
55
import { useCompareLayoutEffect } from '../shared/use-compare-layout-effect';
66

7-
export const useBusSubscribe = <T>(
8-
eventName: HttpEventClassType<T>,
7+
export const useHttpEvent = <T>(
8+
eventType: HttpEventClassType<T>,
99
handler: HttpEventHandler<T>
1010
): void => {
1111
// The event bus.
@@ -31,14 +31,14 @@ export const useBusSubscribe = <T>(
3131
useCompareLayoutEffect(
3232
() => {
3333
// Subscribe to the event and keep track of the subscription.
34-
unsubscribeRef.current = eventBus.subscribe(eventName, handler);
34+
unsubscribeRef.current = eventBus.subscribe(eventType, handler);
3535

3636
// Clean up: unsubscribe the previous event handler.
3737
return () => {
3838
unsubscribe();
3939
};
4040
},
41-
[eventBus, eventName, handler, unsubscribe],
41+
[eventBus, eventType, handler, unsubscribe],
4242
fastCompare
4343
);
4444
};

0 commit comments

Comments
 (0)