npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-native-use-file-upload

v0.2.0

Published

A hook for uploading files using multipart form data with React Native. Provides a simple way to track upload progress, abort an upload, and handle timeouts. Written in TypeScript and no dependencies required.

Downloads

835

Readme

react-native-use-file-upload

A hook for uploading files using multipart form data with React Native. Provides a simple way to track upload progress, abort an upload, and handle timeouts. Written in TypeScript and no dependencies required.

npm version

example app

Installation

yarn add react-native-use-file-upload

Example App

There is an example app in this repo as shown in the above gif. It is located within example and there is a small node server script within example/server here. You can start the node server within example using yarn server.

Usage

import useFileUpload, { UploadItem } from 'react-native-use-file-upload';

// Used in optional type parameter for useFileUpload
interface Item extends UploadItem {
  progress?: number;
}

// ...
const [data, setData] = useState<Item[]>([]);
// The generic type param below for useFileUpload is optional
// and defaults to UploadItem. It should inherit UploadItem.
const { startUpload, abortUpload } = useFileUpload<Item>({
  url: 'https://example.com/upload',
  field: 'file',
  // Below options are optional
  method: 'POST',
  data,
  headers,
  timeout: 60 * 1000, // 60 seconds
  onProgress,
  onDone,
  onError,
  onTimeout,
});

const onPressUpload = async () => {
  const promises = data.map((item) => startUpload(item));
  // Use Promise.all instead if you want to throw an error from a timeout or error.
  // As of October 2022 you have to polyfill allSettled in React Native.
  const result = await Promise.allSettled(promises);
};

Methods

startUpload

Start a file upload for a given file. Returns a promise that resolves with OnDoneData or rejects with OnErrorData.

// Objects passed to startUpload should have the below shape at least (UploadItem type)
startUpload({
  name: 'file.jpg',
  type: 'image/jpg',
  uri: 'file://some-local-file.jpg',
});

abortUpload

Abort a file upload for a given file. The promise from startUpload gets rejected and onError runs if present.

// Pass the uri of a file that started uploading
abortUpload('file://some-local-file.jpg');

Options

const headers = new Headers();
headers.append('Authorization', 'foo');
useFileUpload({ headers });
// OnProgressData type
{
  item: UploadItem; // or a type that inherits UploadItem
  event: ProgressEvent;
};
// event is the XMLHttpRequest progress event object and it's shape is -
{
  loaded: number,
  total: number
}
// OnDoneData type
{
  item: UploadItem; // or a type that inherits UploadItem
  responseBody: string; // eg "{\"foo\":\"baz\"}" (JSON) or "foo"
  responseHeaders: string;
}
// onErrorData type
{
  item: UploadItem; // or a type that inherits UploadItem
  error: string;
}
// OnErrorData type
{
  item: UploadItem; // or a type that inherits UploadItem
  error: string;
  timeout: boolean; // true here
}

FAQs

Do requests continue when the app is backgrounded?

Requests continue when the app is backgrounded on android but they do not on iOS. This can be addressed by using react-native-background-upload.

The React Native team did a heavy lift to polyfill and bridge XMLHttpRequest to the native side for us. There is an open PR in React Native to allow network requests to run in the background for iOS. react-native-background-upload is great but if backgrounding can be supported without any external native dependencies it is a win for everyone.

How can I throttle the file uploads so that I can simulate a real world scenario where upload progress takes time?

You can throttle the file uploads by using ngrok and Network Link Conditioner. Once you have ngrok installed you can start a HTTP tunnel forwarding to the local node server on port 8080 via:

ngrok http 8080

ngrok will generate a forwarding URL to the local node server and you should set this as the url for useFileUpload. This will make your device/simulator make the requests against the ngrok forwarding URL.

You can throttle your connection using Network Link Conditioner if needed. The existing Wifi profile with a 33 Mbps upload works well and you can add a custom profile also. If your upload speed is faster than 100 Mbps you'll see a difference by throttling with Network Link Conditioner. You might not need to throttle with Network Link Conditioner depending on your connection upload speed.

Why send 1 file at a time instead of multiple in a single request?

It is possible to to send multiple files in 1 request. There are downsides to this approach though and the main one is that it is slower. A client has the ability to handle multiple server connections simultaneously, allowing the files to stream in parallel. This folds the upload time over on itself.

Another downside is fault tolerance. By splitting the files into separate requests, this strategy allows for a file upload to fail in isolation. If the connection fails for the request, or the file is invalidated by the server, or any other reason, that file upload will fail by itself and won't affect any of the other uploads.

Why is type and name required in the UploadItem type?

This is because of how React Native abstracts away setting the content-disposition request header for us in their polyfill for FormData. You can see here how that is being done in the getParts function.

License

MIT


Made with create-react-native-library