0.1.11 • Published 4 years ago

react-hook-useapi v0.1.11

Weekly downloads
1
License
ISC
Repository
github
Last release
4 years ago

react-hook-useAPI

handle the restful api easily

Installation

npm install react-hook-useapi or yarn add react-hook-useapi

Configuration

PropTypeRequiredDescription
urlstringYesThe restufl api url, e.g 'api/users'
fetchOptionsobjectNoThe options what needs to add in the request
handleErrorfunctionNo(response) => void It will run this function when response's status code is not success(status code != 2xx)

Props

PropTypeDescriptionDefault
dataobjectUse to store the response json{results:[]}
filterobjectUse to store search params{page:1}
readfunctionFunction(filter) The function use to get the list
getDetailfunctionFucntion(key) The function use to get the item's detail
createfunctionFunction(values) The function use to create new item
updatefunctionFunction(key, values) The function use to update item
delfunctionFunction(key) The function use to delete item

Example

import React, { useEffect } from 'react';
import useAPI from 'react-hook-useapi';

export default const App = () => {
    
 const { data, read, del } = useAPI({ 
        url: '/api/tasks/',
        handleError: res => {
            console.log(res.status);
        }
    });

    useEffect(() => {
        read();
    },[read])
 
  return (
    <div>
        <h3>Example</h3>      
        <table>
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Description</th>
                    <th>Operations</th>
                </tr>    
            </thead>
            <tbody>
                {data.results.map(task => <tr key={task.id}>
                    <td>{task.title}</td>
                    <td>{task.description}</td>
                    <td>
                        <button onClick={() => del(task.id)}>Delete</a>
                    </td>
                </tr>)}   
            </tbody>
        </table>
    </div> 
  )
}