All Projects → kqito → use-tus

kqito / use-tus

Licence: MIT license
React hooks for resumable file uploads using tus

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to use-tus

typescript-nextjs-redux-toolkit-material-ui-example
TypeScript v3.8, Next.js v9, Redux Toolkit, Material-UI v4, react-hooks, SSR live demo
Stars: ✭ 61 (-1.61%)
Mutual labels:  react-hooks
tiny-ui
⚛️ A friendly UI component set for React.js
Stars: ✭ 202 (+225.81%)
Mutual labels:  react-hooks
openzeppelin-network.js
An easy to use and reliable library that provides one line access to Web3 API.
Stars: ✭ 45 (-27.42%)
Mutual labels:  react-hooks
ReSift
A state management library for data fetches in React
Stars: ✭ 39 (-37.1%)
Mutual labels:  react-hooks
use-countdown-timer
React hook exposing a countdown timer with optional expiration reset callbacks
Stars: ✭ 31 (-50%)
Mutual labels:  react-hooks
rex-state
Convert hooks into shared states between React components
Stars: ✭ 32 (-48.39%)
Mutual labels:  react-hooks
use-algolia
Dead-simple React hook to make Algolia search queries. Supports pagination out of the box.
Stars: ✭ 29 (-53.23%)
Mutual labels:  react-hooks
react-hooks
🎣 React Hooks to get hooked on
Stars: ✭ 53 (-14.52%)
Mutual labels:  react-hooks
hx
A simple, easy to use library for React development in ClojureScript.
Stars: ✭ 244 (+293.55%)
Mutual labels:  react-hooks
eslint-config-typescript-unified
🛠️ A unified ESLint configuration with sensible defaults for TypeScript projects.
Stars: ✭ 15 (-75.81%)
Mutual labels:  react-hooks
rapid-react
A light weight interactive CLI Automation Tool 🛠️ for rapid scaffolding of tailored React apps with Create React App under the hood.
Stars: ✭ 73 (+17.74%)
Mutual labels:  react-hooks
quiz
⚛️ Sample Quiz App using React Hooks (useReducer() + useContext()). This app was created for a React Hooks tutorial, if you want to follow the tutorial on Youtube click on the link 👉
Stars: ✭ 26 (-58.06%)
Mutual labels:  react-hooks
use-axios-hooks
axios hooks for common network calls scenarios
Stars: ✭ 27 (-56.45%)
Mutual labels:  react-hooks
react-intersection-observer-hook
React hook to use IntersectionObserver declaratively
Stars: ✭ 58 (-6.45%)
Mutual labels:  react-hooks
React-Playground
Learning reactjs from the ground up (router, redux, thunk, hooks, context, portals, and functional components)
Stars: ✭ 15 (-75.81%)
Mutual labels:  react-hooks
hooks
List of all React hooks using data structures and algorithms
Stars: ✭ 20 (-67.74%)
Mutual labels:  react-hooks
Frontend
마음을 잇는 현명한 소비 '잇다'🤝
Stars: ✭ 19 (-69.35%)
Mutual labels:  react-hooks
think
Instagram clone using React Native with funcional components, React Hooks, React Navigation 4x and Reactotron debugger
Stars: ✭ 20 (-67.74%)
Mutual labels:  react-hooks
react-laravel
A simple crud based laravel app to learn how to use react with laravel.
Stars: ✭ 43 (-30.65%)
Mutual labels:  react-hooks
Nectus
A boilerplate Flask API for a Fullstack Project with some additional packages and configuration prebuilt. ⚙
Stars: ✭ 32 (-48.39%)
Mutual labels:  react-hooks

use-tus

React hooks for resumable file uploads using tus.

Build status Npm version License

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, error, remove } = useTus({ autoAbort, autoStart, uploadOptions });

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: UploadOptions | undefined) (default: undefined)

    • Option to used by upload object that generated by that hooks.
    • For detail type information of UploadOptions, please see here.

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?: UploadOptions) => 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.
  • error (type: Error | undefined)

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

    • Function to reset states.

useTusStore hooks

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

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: UploadOptions | undefined) (default: undefined)

    • Option to used by upload object that generated by that hooks.
    • For detail type information of UploadOptions, please see here.

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.
  • 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']) => UploadOptions | 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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].