React Rest Request
A powerful request library for react apps to coordinate requests in a page in an easy and flexible way.
Installation
yarn add @togglecorp/react-rest-request
Setting up
The core part of the library consists of two higher order components: RequestCoordinator
and RequestClient
.
The coordinator is responsible for coordinating all requests in a page. The clients are used to create individual requests in different components of the page.
Before using this library in a project, it is first recommended to create the actual HOCs using createRequestCoordinator
and createRequestClient
helper functions.
Usage
Coordinator
Use the coordinator at some top level component so that you can create and use multiple request clients in any of its descendents.
Client
The client is used to make actual requests and access the response using props.
Requests settings
When using the RequestClient
HOC, a requests
object needs to be provided which contains details for each request using key, value settings.
Following is the syntax for this requests
object.
Here the request_name
is a unique prop that the component will receive for handling the request and its response. For each such request, it is required to provide a number of key-value pair to define request settings such as its url, request method, body etc.
Each of these settings can either a have fixed value, for example:
Or, it can be a function of signature: ({ props, params }) => {}
which can return a dynamic value, for example:
Here props
is the component's props and params
is something that the user can provide when making the request.
Each request is now made available to the component using request_name
prop. The do
method of this request prop can be used to make the actual request. The do
method can optionally take a params
that can be accessed from the request settings above.
The same prop also contains other info such as the pending status, the response body and any error encountered when making the request, as shown in the example in previous section.
Callbacks
onSuccess
, onFailure
and onFatal
are some callbacks that can be provided as the request settings.
Auto requests
Request can be triggered automatically when the component mounts:
Similarly a request can be retriggered everytime some prop changes:
Because, user cannot provide params when these requests are auto triggered,
a method setDefaultParams
is provided. User can then set default params to use
when actual params is not provided when making the request.