1.0.12 • Published 4 years ago
@mistenkt/use-rest-api v1.0.12
use-rest-api
A customizable REST Api and data manager hook for your React application
Installation
yarn add @mistenkt/use-rest-api
Usage
Initialize the
ApiProvider
in yourApp.js
file and provide the required params.import React from 'react'; import {ApiProvider} from '@mistenkt/use-rest-api'; const apiResources = { users: { endpoint: '/user' }, posts: { endpoint: '/post', } }; const App = () => { return ( <ApiProvider baseUrl="https://locahost/api" resources={apiResources} > {/* The rest of your app*/} </ApiProvider> ) }; export default App;
Use the
useApi
hook inside your containers/components that want to consume api dataimport React from 'react'; import {useApi} from '@mistenkt/use-rest-api'; const UserIndex = () => { const [users, loading, update, reset] = useApi('users.list'); if(loading) return ( <div>Loading...</div> ) if(!users && !loading) return ( <div>No users</div> ) return ( <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ) } export default UserIndex;
To send create/update request to the api use the
useProducer
hook.import React from 'react'; import {useApi, useProducer} from '@mistenkt/use-rest-api'; const UserIndex = () => { const [users, loading] = useApi('users.list'); const [produce, produceLoading, validationErrors] = useProducer({ onSuccess: data => console.log('Success callback', data), onFail: err => console.log('Fail callback', data), onValidationError: errors => console.log('Validation error callback', errors) }); const createUser = () => { produce('users.create', { name: 'foo' }) }; if(loading) return ( <div>Loading...</div> ) if(!users && !loading) return ( <div>No users</div> ) return ( <> <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> <button onClick={createUser}>Create user</button> </> ) } export default UserIndex;
Api Documentation
Ful api documentation coming soon.
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.