react-custom-fetch-hook

1.0.4 • Public • Published

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>
  }
};

Package Sidebar

Install

npm i react-custom-fetch-hook

Weekly Downloads

1

Version

1.0.4

License

ISC

Unpacked Size

3.18 kB

Total Files

3

Last publish

Collaborators

  • imrajput