DEV Community

H2rmone
H2rmone

Posted on

How to make http request with React Hooks?

This is my first post at dev.to. I'm going to introduce a custom React Hooks that help making http request -- use-request

I have seen a lot of request libraries written with React Hooks but none of them I like. Most of them put the client in it which causes less flexibility. When switch to use-request, it’s up to you to use axios or fetch. Pass the function that encapsulates the client and the api request into the useRequest function, then you can get the state of the request and callback functions. With typescript support, the input parameters of the request callback function can also be displayed accurately according to the type definition of api function. Let's take a look at how it works!

Feature

  • πŸ‘• Typescript support.
  • πŸ—œοΈ 1.3kb after minified without gzip.
  • πŸ“€ Easy to use with different request client.

Install

yarn add @rekindle/use-request

Usage

import useRequest from '@rekindle/use-request'
import getFooApi from '@/utils/axios'

function App() {
  const [{ loading, error, data }, fetch] = useRequest(getFooApi)

  function handleClick() {
    fetch()
  }

  useEffect(() => {
    fetch()
  }, [fetch])

  if (loading) return <div>loading...</div>
  if (error) return <div>error</div>

  return (
    <div>
      <p>{data && data.text}</p>
      <button onClick={handleClick}>refetch</button>
    </div>
  )
}

Api

type useRequest = (api, initialState) => [state, memoizedRequestCallback]

Notice: Why momoized request callback ?

Reference: Is it safe to omit functions from the list of dependencies?

If you want a deep dive on useEffect and dependencies, it's here: https://overreacted.io/a-complete-guide-to-useeffect/

Oldest comments (0)