React hook for fetching/refetching data from an API endpoint
1import { useFetch } from 'react-modern-hooks'23const Demo = () => {4 const { data, loading, refetch, processRequest, error } = useFetch(5 'https://jsonplaceholder.typicode.com/todos'6 )78 if (loading) return <p>Loading...</p>910 if (error || !data) return <p>{error}</p>1112 const handleRequest = () => {13 processRequest('https://jsonplaceholder.typicode.com/todos', {14 method: 'POST'15 })16 }1718 return (19 <div>20 <p>Data Fetched</p>21 <button onClick={refetch}>Refetch</button>22 <button onClick={handleRequest}>Click to Process New Request</button>23 </div>24 )25}
url - The API endpoint to fetch data from
options - optional parameters allowed to be passed when fetching data from an endpoint
data - Result returned data from the api endpoint
error - Error response returned incase something goes wrong during data fetching
loading - Loading state returned when data is still loading from the API endpoint
refetch - Refetch function to refetch data
processRequest - A helper function to process requests made via POST or PATCH or DELETE methods