1.1.1 • Published 5 months ago

react-fetch-with-progress v1.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

react-fetch-with-progress

NPM Version npm downloads NPM Downloads NPM License

A React Hook for fetching data with download progress tracking.

Installation

yarn add react-fetch-with-progress

or

npm i react-fetch-with-progress

Hook Reference

All-in-one hook

const { progress, eta, response, fetchWithProgress } = useFetchWithProgress();

Hook Returns

PropertyTypeDescription
progressnumberCurrent download progress (0 - 100).
etanumberEstimated time remaining (in milliseconds).
responseResponse \| nullThe full fetch response object.
fetchWithProgress(url: string, options?: RequestInit, callback?: FetchWithProgressCallback) => Promise<Response>Function to start fetching with progress tracking.

API Reference

fetchWithProgress(url, options?, callback?)

Parameters:

ParameterTypeDescription
urlstringThe API endpoint to fetch data from.
optionsRequestInit (optional)Optional fetch configuration (headers, method, body, etc.).
callbackFetchWithProgressCallback (optional)Optional callback function to track the progress of the request.

FetchWithProgressCallback

({ progress, eta }) => void | Parameter | Type | Description | |-----------|------|-------------| | progress | number | The current progress of the request as a percentage (0-100). | | eta | number | Estimated time remaining for the request to complete, in milliseconds. |

Returns:

Promise<Response> - Resolves to the fetch response object.

Example

// React function component:
export default function App() {
  const { progress, eta, response, fetchWithProgress } = useFetchWithProgress();

  const url = 'https://example.com/image.jpg';

  const handleFetchImage = () => {
    // Same as native `fetch`
    fetchWithProgress(url, {}, callback)
      .then(response => {
        console.log("Fetch complete!", response);
      })
      .catch((error) => {
        console.error("Fetch failed:", error);
      });
  };

  // Callback function to track the progress of the request.
  const callback = ({ progress, eta }) => {
    console.log(`Progress: ${progress}%`);
    console.log(`ETA: ${eta}ms`);
  }
  
  return (
    <div>
      <button onClick={handleFetchImage}>Fetch Image</button>
      <div>
        Loading progress: 
        <progress max="100" value={progress ?? 0} />
        {progress.toFixed(1)}%
      </div>
      <div>ETA: {(eta / 1000).toFixed(1)}s</div>
    </div>
  )
}
1.1.1

5 months ago

1.1.0

5 months ago

1.0.1

6 months ago

1.0.0

6 months ago

0.0.2

6 months ago

0.0.1

6 months ago