react-use-fetch

React hook for using fetch.

Usage no npm install needed!

<script type="module">
  import reactUseFetch from 'https://cdn.skypack.dev/react-use-fetch';
</script>

README

react-use-fetch

CircleCI Coverage Status

React hook for using fetch.

Installation

Using npm:

$ npm install --save react-use-fetch

Using yarn:

$ yarn add react-use-fetch

This module uses React's upcoming hooks feature. To try this out you'll also need to install the 16.7.0-alpha.0 version of react and react-dom:

$ yarn add react@16.7.0-alpha.0 react-dom@16.7.0-alpha.0

Usage

import React from 'react';
import useFetch, { useJsonResponse } from 'react-use-fetch';

function Example() {
  const { response } = useFetch('https://api.github.com/users/bsonntag');
  const [json] = useJsonResponse(response);

  if (!json) {
    return <p>Loading...</p>;
  }

  if (!response.ok) {
    return <p>Error: {json.message}</p>;
  }

  return (
    <>
      <h1>{json.name}</h1>
      <img src={json.avatar_url} />
    </>
  );
}

API

useFetch(input: string | Request, init?: Object): {
  error: ?Error,
  response: ?Response
}

Receives the same arguments as fetch and returns an object with the response and the request error.

useJsonResponse(response: ?Response): [?Object, ?Error];

Receives a fetch response and returns a tuple with the result of response.json() and the error of parsing. If the response is null or undefined nothing is done.

Contributing

Please feel free to submit any issues or pull requests.

License

MIT