1.0.3 • Published 3 years ago

react-api-hook v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

react-api-hook

This package was created to simplify the handling of REST calls in React.

To use this package, simply declare it in the component, inserting the endpoint and possible configurations (headers, body, etc.) and call it with the appropriate sendRequest function.

The state of the call can be read from the state variable.

Finally, to cancel the request, instead, it is sufficient to call the cancelRequest function.

The state of the call has the following values:

  • idle
  • loading
  • success
  • failure
  • inAbort
  • canceled

In case it is success or failure, it will also have the properties data and error respectively.

statetypedescription
idlestringThe hook is ready to send a request.
loadingstringThe hook sent the request, is waiting for response.
successstringThe hook succesfully received the response. Is ready to send another request.
failurestringThe hook catches an error. Is ready to send another request.
inAbortstringThe hook is canceling the request.
canceledstringThe hook canceled the request. Is ready to send another request.
dataResponseThe received response. You can parse using json() function
erroranyInformation about the catched error.

Example:

import React,  {  useEffect  }  from  "react";
import useAPIHook from  "react-api-hook";

function  App()  {
    const  [status,  send,  cancel]  =  useAPIHook(
	    "https://jsonplaceholder.typicode.com/posts",
	    {  method:  "GET"  },
    );
    
    useEffect(()  =>  {
	    if (status.status  ===  "success") {
		    console.log(status.data);
		    //status.data.json() for the body of response  
	    }
	    if(status.status  ===  "failure") {
		    console.log(status.error);
	    }
    }, [status]);
    
    return (
	    <div  className="App">
			<header  className="App-header">
				<div>{status.status}</div>
			    <div>
				    <button  onClick={send}>start fetching</button>
				    <button  onClick={cancel}>stop fetching</button>
			    </div>
			</header>
	    </div>
    );
}

export  default  App;