logoReact Modern Hooks

Documentation

Getting Started

Installation

Hooks Overview

useFetch( )useCopyToClipboard( )useNetwork( )useFullScreen( )useGeolocation( )useSelectedText( )useStateCallback( )useResize( )useSearch( )useImageDownload( )

useFetch( )

React hook for fetching/refetching data from an API endpoint

Usage

1import { useFetch } from 'react-modern-hooks'
2
3const Demo = () => {
4 const { data, loading, refetch, processRequest, error } = useFetch(
5 'https://jsonplaceholder.typicode.com/todos'
6 )
7
8 if (loading) return <p>Loading...</p>
9
10 if (error || !data) return <p>{error}</p>
11
12 const handleRequest = () => {
13 processRequest('https://jsonplaceholder.typicode.com/todos', {
14 method: 'POST'
15 })
16 }
17
18 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}

References

Input Variables

url - The API endpoint to fetch data from

options - optional parameters allowed to be passed when fetching data from an endpoint

Output Variables

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