README
api-client-react
Small library to simplify the connection with api in React.
With a simple higher-order component (HOC), you can get:
- The following props for section:
{ loading, error, data, complete }
- The following prop:
apiClient
, with which you can interact with API.
- Note: Each API call is stored in a section
Examples
Getting Started
Installation
You can install with NPM: api-client-react
npm i --save api-client-react
Create your component and connect
import { connectApiClient } from "api-client-react";
const ExampleconnectApiClientComponent = ({ users }) => {
if (users.loading) {
return <p>loading</p>;
}
if (users.error) {
return <p>Error</p>;
}
if (users.data) {
return (
<ol>
{users.data.map(b => (
<li key={b.name}>{b.name}</li>
))}
</ol>
);
}
}
const config = {
apiConfig: { // Same object: https://github.com/axios/axios#axios-api
method: "get",
url: "https://jsonplaceholder.typicode.com/users"
},
section: "users" // Reference section
};
const componentSections = ["users"];
export const ExampleconnectApiClient = connectApiClient(componentSections, config)(ExampleconnectApiClientComponent);
NOTE: If you want to make the call in a method, it is also possible: View codesandbox.
Note: Important to send properties apiConfig
and section
in config property.
Doc
Functions
| function (render props) | params | description |
|--|--|--|
| apiClient.fetch( apiConfigObject, "sectionExample" )
| apiConfigObject: Same object: https://github.com/axios/axios#axios-api | Execute axios fetch with the configuration provided And associate the response to your section |
Render props
You will receive a props for each section that is an object composed of:
| prop | types | default value | description |
|--|--|--|--|
| error
| error
| false
| Api error |
| data
| result
| | Data response |
| loading
| boolean
| false
| Only true
during call response period. |
| complete
| boolean
| false
| Only true
when api call is finished. |
MIT License.