Skip to content

Haqverdi/react-usefetch

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

76 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

useFetch

🐶 React hook for making isomorphic http requests

Need to fetch some data? Try this one out. It's an isomorphic fetch hook. That means it works with SSR (server side rendering).

Examples

Installation

yarn add use-http

Usage

import useFetch from 'use-http'

function App() {
  // add whatever other options you would add to `fetch` such as headers
  const options = {
    method: 'POST',
    body: {}, // whatever data you want to send
  }
  
  var [data, loading, error] = useFetch('https://example.com', options)
  
  // want to use object destructuring? You can do that too like:
  var { data, loading, error } = useFetch('https://example.com', options)
  
  if (error) {
    return 'Error!'
  }
  
  if (loading) {
    return 'Loading!'
  }
  
  return (
    <code>
      <pre>{data}</pre>
    </code>
  )
}

Or you can use one of the nice helper hooks. All of them accept the second options parameter.

import { useGet, usePost, usePatch, usePut, useDelete } from 'use-http'

function App() {
  const [data, loading, error] = useGet('https://example.com')
  
  if (error) {
    return 'Error!'
  }
  
  if (loading) {
    return 'Loading!'
  }
  
  return (
    <code>
      <pre>{data}</pre>
    </code>
  )
}

Hooks

Option Description
useFetch The base hook
useGet Defaults to a GET request
usePost Defaults to a POST request
usePut Defaults to a PUT request
usePatch Defaults to a PATCH request
useDelete Defaults to a DELETE request

Options

Option Description
options This is exactly what you would pass to the normal js fetch

Todos

  • Make abortable (add abort to abort the http request)
  • Make work with React Suspense
  • Allow option to fetch on server instead of just having loading state
  • Allow option for callback for response.json() vs response.text()
  • Add a refetch option
  • Potentially add syntax like useFetch({ url: '', method: '' })

About

🐶 React hook for making isomorphic http requests

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 73.6%
  • HTML 13.9%
  • CSS 7.6%
  • Shell 4.9%