Uplo
Client

React

Installation

npm i @uplo/react

Usage

Add a provider

// App.js

import { UploProvider } from '@uplo/react'

export const App = ({ children }) => {
  return <UploProvider host={process.env.API_URL}>{children}</UploProvider>
}

Provider options

  • host (required): URL of your API.
  • mountPath = '/uploads': Path where the Uplo routes are mounted.
  • headers: Extra headers for requests to your API, as an object or a function (can be async) that runs before each request.
  • credentials: fetch credentials for requests to your API.

If your upload route needs authentication (see Hono or Fastify), pass the token with headers:

<UploProvider
  host={process.env.API_URL}
  headers={async () => ({ Authorization: `Bearer ${await getAccessToken()}` })}
>
  {children}
</UploProvider>

Use credentials: 'include' to send cookies when the API is on another domain.

These options are only used for requests to your API. Files are uploaded to storage with the headers your API returns, so tokens are not sent to the storage provider.

Use direct upload

import { useDirectUpload } from '@uplo/react'

export const Page = () => {
  const {
    uploads,
    uploadFile,
    uploading,
    error,
    signedIds,
    clear: clearUploads,
  } = useDirectUpload('user.avatar', { multiple: false })

  const onFileChange = async (e: ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files) return

    const file = e.target.files[0]

    try {
      const uploadData = await uploadFile({ file })

      if (uploadData.signedId) {
        await updateCurrentUser({ avatarSignedId: uploadData.signedId })
      }
    } catch (e) {
      // Capture exception
    }
  }

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

Metadata

Pass metadata with the file to store it with the blob:

await uploadFile({ file, metadata: { caption: 'Profile photo' } })

It is stored as blob.metadata.client, apart from metadata written on the server, and is not trusted. See Metadata for limits.

On this page