1.0.4 • Published 2 years ago

react-custom-fetch-hook v1.0.4

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

react-custom-fetch-hook

GitHub issues npm version GitHub stars

React hook for conveniently use Fetch API. It will take url and the extra header if needed.

import useFetch from 'react-custom-fetch-hook'

function CustomHook() {
    const {data,loading} = useFetch('https://quotable.io/quotes',{})
  
    if(loading){
        return <h3>Loading...</h3>
    }
    return (
        <div>
            {data.results.map((result) => (
                   <p key={result._id}>{result.content}</p>
            ))}
        </div>
    )
}

useFetch accepts the same arguments as fetch function.

Installation

Install it with npm:

npm i react-custom-fetch-hook --save

Error handling

The useFetch hook returns an error field at any fetch exception. The error field extends Error and has status and statusText fields equal to Response.

function CustomHook() {
  const {data,loading ,error } = useFetch("https://quotable.io/quotes");

  if (error) {
    return <div>
      <p>Code: ${error.status}</p>
      <p>Message: ${error.statusText}</p>
    </div>
  }
};