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

use-tus

v0.8.2

Published

React hooks for resumable file uploads using tus-js-client

Downloads

4,739

Readme

Features

  • Resumable file uploads on react.
  • Lightweight and simple interface hooks.
  • Managing the Upload by using context.
  • TypeScript support.

Demo

You can try the use-tus demo.

Installation

You can install the package from npm.

npm install use-tus tus-js-client

or

yarn add use-tus tus-js-client

Usage

We can use useTus as following.

import { useTus } from 'use-tus'

const Uploader = () => {
  const { upload, setUpload, isSuccess, error, remove } = useTus();

  const handleSetUpload = useCallback((event: ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files.item(0);

      if (!file) {
        return;
      }

      setUpload(file, {
        endpoint: 'https://tusd.tusdemo.net/files/',
        metadata: {
          filename: file.name,
          filetype: file.type,
        },
      });
    },
    [setUpload]
  );

  const handleStart = useCallback(() => {
    if (!upload) {
      return;
    }

    // Start to upload the file.
    upload.start();
  }, [upload]);

  return (
    <div>
      <input type="file" onChange={handleSetUpload} />
      <button type="button" onClick={handleStart}>
        Upload
      </button>
    </div>
  );
};

API

useTus hooks

const { upload, setUpload, isSuccess, isAborted, isUploading, error, remove } = useTus({ autoAbort, autoStart, uploadOptions, Upload });

useTus is a hooks that creates an object to perform Resumable file upload.

Arguments

  • autoAbort (type: boolean | undefined) (default: true)

    • Whether or not to automatically abort uploads when useTus hooks is unmounted.
  • autoStart (type: boolean | undefined) (default: false)

    • Whether or not to start upload the file after setUpload function.
  • uploadOptions (type: TusHooksUploadFnOptions | undefined) (default: undefined)

    • Option to used by upload object that generated by that hooks.
  • Upload (type: Upload | undefined) (default: undefined)

    • Option to specify customized own Upload class with this hooks.

About uploadOptions

This option extends the UploadOptions provided by tus-js-client, but it has been extended so that every callback can receive the upload instance as the final argument.

For detail type information of UploadOptions, please see here.

e.g.

setUplaod(file, {
  onSuccess: (upload) => {
    console.log(upload.url)
  },
  onError: (error, upload) => {
    console.log(error)

    setTimeout(() => {
      upload.start()
    }, 1000)
  }
})

Returns

  • upload (type: tus.Upload | undefined)

    • Object to be used when performing Resumable file upload.
    • This value is undefined unless the setUpload function called.
    • For detail usage, please see here
  • setUpload (type: (file: tus.Upload['file'], options?: TusHooksUploadFnOptions) => void)

    • Function to create an Upload.
    • The property specified in uploadOptions will be overwritten if property of options are speicified.
  • isSuccess (type: boolean)

    • Whether the upload was successful or not.
  • isAborted (type: boolean)

    • Whether the upload was aborted or not.
  • isUploading (type: boolean)

    • Indicates if an uploading is in progress or not.
  • error (type: Error | undefined)

    • Error when upload fails.
  • remove (type: () => void)

    • Function to reset states.

useTusStore hooks

const { upload, setUpload, isSuccess, isAborted, isUploading, error, remove } = useTusStore(cacheKey, { autoAbort, autoStart, uploadOptions, Upload  });

useTusStore is a hooks that creates an object for resumable file upload and stores it in a context.

This hooks is useful when you want to handle uploads across pages or components.

Note that using useTusStore hooks, the TusClientProvider must be specified as the parent or higher element.

Arguments

  • cacheKey (type: string)

    • Specify the key associated with the Upload object is created by setUpload function.
  • autoAbort (type: boolean | undefined) (default: true)

    • Whether or not to automatically abort uploads when useTusStore hooks is unmounted.
  • autoStart (type: boolean | undefined) (default: false)

    • Whether or not to start upload the file after setUpload function.
  • uploadOptions (type: TusHooksUploadFnOptions | undefined) (default: undefined)

    • Option to used by upload object that generated by that hooks.
    • For detail type information of TusHooksUploadFnOptions, please see here.
  • Upload (type: Upload | undefined) (default: undefined)

    • Option to specify customized own Upload class with this hooks.

Returns

  • upload (type: tus.Upload | undefined)
    • Object to be used when performing Resumable file upload.
    • This value is undefined unless the setUpload function called.

Returns

  • upload (type: tus.Upload | undefined)

    • Object to be used when performing Resumable file upload.
    • This value of the Upload associated with the cacheKey in the TusClientProvider. If not present, undefined.
    • For detail usage, please see here
  • setUpload (type: (file: tus.Upload['file'], options?: tus.Upload['options']) => void)

    • Function to create an Upload.
    • The property specified in uploadOptions will be overwritten if property of options are speicified.
  • isSuccess (type: boolean)

    • Whether the upload was successful or not.
  • isAborted (type: boolean)

    • Whether the upload was aborted or not.
  • isUploading (type: boolean)

    • Indicates if an uploading is in progress or not.
  • error (type: Error | undefined)

    • Error when upload fails.
  • remove (type: () => void)

    • Function to delete the Upload associated with cacheKey.

TusClientProvider

() => (
  <TusClientProvider defaultOptions={defaultOptions}>
    {children}
  </TusClientProvider>
)

TusClientProvider is the provider that stores the Upload with useTusStore hooks.

Props

  • defaultOptions (type: (file: tus.Upload['file']) => TusHooksUploadFnOptions | undefined)
    • An object containing the default options used when creating a new upload. detail

useTusClient

const { state, removeUpload, reset } = useTusClient();

useTusClient is a hooks that can be used to retrieve and reset the state of a TusClientProvider.

Returns

  • state (type: { [cacheKey: string]: UploadState | undefined })

    • Upload information associated with cacheKey
  • removeUpload (type: (cacheKey: string) => void)

    • Remove the upload instance associated with the specified cacheKey.
  • reset (type: () => void)

    • Initialize the value of TusClientProvider

Examples

The following are some example of how to use use-tus.

Uploading a file

The setUpload and upload.start functions can be used to perform resumable file uploads.

import { useTus } from 'use-tus'

const Uploader = () => {
  const { upload, setUpload } = useTus();

  const handleSetUpload = useCallback((event: ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files.item(0);

      if (!file) {
        return;
      }

      setUpload(file, {
        endpoint: 'https://tusd.tusdemo.net/files/',
        metadata: {
          filename: file.name,
          filetype: file.type,
        },
      });
    },
    [setUpload]
  );

  const handleStart = useCallback(() => {
    if (!upload) {
      return;
    }

    // Start upload the file.
    upload.start();
  }, [upload]);

  return (
    <div>
      <input type="file" onChange={handleSetUpload} />
      <button type="button" onClick={handleStart}>
        Upload
      </button>
    </div>
  );
};

It is also possible to automatically upload files after setUpload by specifying the autoStart option.

import { useTus } from 'use-tus'

const Uploader = () => {
  const { upload, setUpload } = useTus({ autoStart: true });

  const handleSetUpload = useCallback((event: ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files.item(0);

      if (!file) {
        return;
      }

      setUpload(file, {
        endpoint: 'https://tusd.tusdemo.net/files/',
        metadata: {
          filename: file.name,
          filetype: file.type,
        },
      });
    },
    [setUpload]
  );
  return (
    <input type="file" onChange={handleSetUpload} />
  );
};

Aborting a file upload

You can abort the upload by using the upload.abort function.

import { useTus } from 'use-tus'

const Aborter = () => {
  const { upload } = useTus();

  const handleAbort = useCallback(() => {
    if (!upload) {
      return;
    }

    upload.abort();
  }, [upload]);

  return (
    <div>
      <button type="button" onClick={handleAbort}>
        Abort
      </button>
    </div>
  );
};

You can also specify the autoAbort option to automatically stop uploads when unmounting hooks.

import { useTus } from 'use-tus'

const Uploader = () => {
  const { upload, setUpload } = useTus({ autoAbort: true });

  // omitted...
};

Default options of upload

You can specify default options in the defaultOptions props of the TusClientProvider.

import { useTusStore, DefaultOptions, TusClientProvider } from 'use-tus'

const defaultOptions: DefaultOptions = (contents) => {
  const file = contents instanceof File ? contents : undefined;

  return {
    endpoint: 'https://tusd.tusdemo.net/files/',
    metadata: file
      ? {
          filename: file.name,
          filetype: file.type,
        }
      : undefined,
  };
};

const App = () => (
  <TusClientProvider defaultOptions={defaultOptions}>
    <Uploader />
  </TusClientProvider>
);

const Uploader = () => {
  const { setUpload } = useTusStore('cacheKey', { autoStart: true });

  const handleSetUpload = useCallback((event: ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files.item(0);

      if (!file) {
        return;
      }

      // You no longer need to specify the options associated with upload.
      // If specified, it will override defaultOptions.
      setUpload(file);
    },
    [setUpload]
  );

  return (
    <div>
      <input type="file" onChange={handleSetUpload} />
    </div>
  );
};

Specify upload key

If you specify cacheKey as an argument to useTusStore, you can get the upload associated with it. This is useful for cross-page file uploads.

const SelectFileComponent = (file: File) => {
  // Create upload accosiated with 'upload-thumbnail' key
  const { setUpload } = useTusStore('upload-thumbnail')

  setUpload(file)
}

const UploadFileComponent = () => {
  const { upload } = useTusStore('upload-thumbnail')

  upload.start()
}

License

MIT © kqito