console.log("also dropped", e) })}>
```
```
--------------------------------
### Session Store Creation and File Fingerprinting
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/guides/upload.mdx
Provides utility functions for creating in-memory or browser-backed upload session stores and for generating file fingerprints based on metadata.
```typescript
createMemoryUploadSessionStore(); // in-process only — gone on reload, gone between tabs
createBrowserUploadSessionStore({ prefix? }); // localStorage-backed, SSR-safe (no-op without `window`)
createFileFingerprint(file: File): string; // name+size+type+lastModified+webkitRelativePath, not file contents
```
--------------------------------
### Import useMediaDrop Hook
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/use-media-drop.mdx
Import the useMediaDrop hook from the react-mediadrop library.
```typescript
import { useMediaDrop } from "react-mediadrop";
```
--------------------------------
### Import necessary hooks and transport
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/getting-started/installation.mdx
Import the useMediaDrop hook and the createXhrUploadTransport function from the react-mediadrop library. Remember to add 'use client' at the top of your file if using Next.js App Router.
```javascript
import { useMediaDrop } from "react-mediadrop";
import { createXhrUploadTransport } from "react-mediadrop/xhr-upload";
```
--------------------------------
### Composing Custom Drop Handlers
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/use-media-drop.mdx
Shows how to compose custom event handlers with the hook's default handlers. Custom handlers execute before the hook's handlers.
```tsx
console.log("also dropped", e) })}>
```
--------------------------------
### createBrowserUploadSessionStore Function
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/types.mdx
Creates a browser-based implementation of the MediaDropUploadSessionStore, typically using localStorage or sessionStorage.
```APIDOC
## createBrowserUploadSessionStore Function
### Description
Creates a browser-based implementation of the MediaDropUploadSessionStore, typically using localStorage or sessionStorage.
### Function Signature
```typescript
function createBrowserUploadSessionStore(options?: { prefix?: string }): MediaDropUploadSessionStore;
```
```
--------------------------------
### Import createXhrUploadTransport
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/xhr-upload.mdx
Import the necessary function from the react-mediadrop/xhr-upload package.
```typescript
import { createXhrUploadTransport } from "react-mediadrop/xhr-upload";
```
--------------------------------
### createMemoryUploadSessionStore Function
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/types.mdx
Creates an in-memory implementation of the MediaDropUploadSessionStore.
```APIDOC
## createMemoryUploadSessionStore Function
### Description
Creates an in-memory implementation of the MediaDropUploadSessionStore.
### Function Signature
```typescript
function createMemoryUploadSessionStore(): MediaDropUploadSessionStore;
```
```
--------------------------------
### React MediaDrop Hook Initialization
Source: https://github.com/autorender/react-mediadrop/blob/main/README.md
Initialize the useMediaDrop hook in a React component. Configure restrictions for accepted file types and maximum number of files.
```tsx
import { useMediaDrop } from "react-mediadrop";
const { getRootProps, getInputProps, files } = useMediaDrop({
restrictions: { accept: ["image/png", "image/jpeg"], maxFiles: 5 },
});
```
--------------------------------
### MediaDropUploadSessionStore Interface and Factory Functions
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/types.mdx
Defines the interface for managing upload session data and provides factory functions for creating memory-based and browser-based session stores.
```typescript
type MediaDropUploadSessionStore = {
get(key: string): Promise;
set(key: string, value: unknown): Promise;
remove(key: string): Promise;
};
function createMemoryUploadSessionStore(): MediaDropUploadSessionStore;
function createBrowserUploadSessionStore(options?: {
prefix?: string;
}): MediaDropUploadSessionStore;
function createFileFingerprint(file: File): string;
```
--------------------------------
### Configure Upload Behavior
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/guides/upload.mdx
Set the maximum number of concurrent uploads, the number of retries for failed uploads, and the grace period for cancellation.
```typescript
useMediaDrop({
transport,
concurrency: 3, // max uploads in flight at once. Default 1 (sequential).
retries: 2, // retries *after* the first attempt, shared for every file. Default 0.
retryDelays: [1000, 2000, 4000], // backoff per retry; last value repeats if exhausted.
cancelGraceMs: 5000, // force-free a slot this long after cancel if the transport never settles. Default 5000.
});
```
--------------------------------
### Minimal Fetch-based Upload Transport
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/guides/custom-transport.mdx
A basic implementation of a custom upload transport using the Fetch API. It sends the file via POST and reports progress only upon completion due to Fetch's lack of built-in upload progress events.
```typescript
import { createHttpError, type UploadTransport } from "react-mediadrop";
function createMyTransport(options: { endpoint: string }): UploadTransport {
return {
aSync upload(file, { onProgress, signal }) {
const response = await fetch(options.endpoint, {
method: "POST",
body: file.file,
signal,
});
if (!response.ok) {
throw createHttpError(`Upload failed: ${response.status}`, response.status);
}
onProgress({ loaded: file.size, total: file.size });
return { response: await response.json() };
},
};
}
```
--------------------------------
### Create XHR Upload Transport
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/xhr-upload.mdx
Instantiate the transport with an endpoint and optional fields. This transport is used with the useMediaDrop hook for managing uploads.
```typescript
import { useMediaDrop } from "react-mediadrop";
import { createXhrUploadTransport } from "react-mediadrop/xhr-upload";
const transport = createXhrUploadTransport({
endpoint: "/api/upload", // or (file) => `/api/upload/${file.id}` for a per-file URL
fields: { folder: "avatars" }, // extra multipart fields
});
const { files } = useMediaDrop({ transport, concurrency: 3, retries: 2 });
```
--------------------------------
### RetryOptions and withRetry Function
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/types.mdx
Defines options for configuring retry logic and the `withRetry` utility function for handling asynchronous operations with retries.
```typescript
type RetryOptions = {
retries?: number;
retryDelays?: number[];
shouldRetry?: (error: unknown, attemptNumber: number) => boolean;
jitter?: number; // 0–1
};
function withRetry(
attempt: (attemptNumber: number) => Promise,
options: RetryOptions,
signal: AbortSignal,
): Promise;
```
--------------------------------
### Add "use client" Directive for React MediaDrop
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/getting-started/installation.mdx
When using `useMediaDrop` in a Next.js project with React Server Components, you must add the 'use client' directive at the top of your file. This ensures that the component runs in a Client Component environment, as `useMediaDrop` relies on hooks like `useState` and `useEffect` which are not available in Server Components.
```tsx
"use client";
import { useMediaDrop } from "react-mediadrop";
```
--------------------------------
### createFileFingerprint Function
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/types.mdx
Generates a unique fingerprint for a given File object, useful for identifying upload sessions.
```APIDOC
## createFileFingerprint Function
### Description
Generates a unique fingerprint for a given File object, useful for identifying upload sessions.
### Function Signature
```typescript
function createFileFingerprint(file: File): string;
```
```
--------------------------------
### useMediaDrop Hook
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/use-media-drop.mdx
The useMediaDrop hook is a headless function that manages file drop and upload interactions. It accepts an options object to configure its behavior and returns a set of properties and methods for interacting with the file input and dropzone.
```APIDOC
## useMediaDrop Hook
### Description
Provides headless functionality for file drops and uploads. Users own the markup and control the UI.
### Signature
```ts
function useMediaDrop(options?: {
restrictions?: MediaDropRestrictions;
validator?: MediaDropValidator;
noClick?: boolean; // disable click-to-open on the root
noKeyboard?: boolean; // disable Space/Enter-to-open and focus tracking
noDrag?: boolean; // disable the root's drag/drop handling
transport?: UploadTransport; // opt into upload — see below
concurrency?: number; // max uploads in flight at once. Default 1.
retries?: number; // retries after the first attempt. Default 0.
retryDelays?: number[]; // backoff per retry.
cancelGraceMs?: number; // force-free a slot after cancel. Default 5000.
}): UseMediaDropResult;
```
### Options
- **`restrictions`**: Configuration for file type and size restrictions.
- **`validator`**: A custom function for validating files.
- **`noClick`** (boolean): If true, disables click-to-open functionality on the root element.
- **`noKeyboard`** (boolean): If true, disables keyboard activation (Space/Enter) and focus tracking.
- **`noDrag`** (boolean): If true, disables drag and drop handling on the root element.
- **`transport`** (UploadTransport): Enables upload functionality. See the Upload guide for details.
- **`concurrency`** (number): Maximum number of concurrent uploads. Defaults to 1.
- **`retries`** (number): Number of retries for failed uploads. Defaults to 0.
- **`retryDelays`** (number[]): Array of delays for upload retries.
- **`cancelGraceMs`** (number): Time in milliseconds to force-free a slot after a cancel. Defaults to 5000.
### Return Value (`UseMediaDropResult`)
- **`files` / `acceptedFiles` / `rejectedFiles`** (`MediaDropFile[]`): An array of files, filtered by their status.
- **`isDragActive` / `isDragAccept` / `isDragReject`** (`boolean`): State indicating the drag-and-drop status of the dropzone.
- **`isFocused`** (`boolean`): Indicates if the root element has keyboard focus. Always `false` when `noKeyboard` is set.
- **`isDragGlobal`** (`boolean`): Indicates if a file drag is happening anywhere on the document.
- **`removeFile(id)` / `clearFiles()`** (`() => void`): Functions to remove individual files by ID or clear all files. Cancels in-flight uploads for removed files.
- **`open()`** (`() => void`): Imperatively opens the native file picker dialog.
- **`getRootProps(arg?)`** (`() => RootProps`): Returns props to be spread onto the root element, including drag/drop, click/keyboard handlers, `role`, and `tabIndex`.
- **`getInputProps(arg?)`** (`() => InputProps`): Returns props for the hidden file input element.
*Note: If `transport` is provided, additional upload-related methods like `uploadFile`, `uploadAll`, `cancelUpload`, `cancelAllUploads`, and `retryUpload` are also returned.*
```
--------------------------------
### withRetry Function
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/types.mdx
A utility function that wraps an asynchronous operation with retry logic based on the provided options.
```APIDOC
## withRetry Function
### Description
A utility function that wraps an asynchronous operation with retry logic based on the provided options.
### Function Signature
```typescript
function withRetry(
attempt: (attemptNumber: number) => Promise,
options: RetryOptions,
signal: AbortSignal,
): Promise;
```
```
--------------------------------
### RetryOptions Type
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/types.mdx
Configuration options for retrying operations, including the number of retries, delay intervals, and custom retry logic.
```APIDOC
## RetryOptions Type
### Description
Configuration options for retrying operations, including the number of retries, delay intervals, and custom retry logic.
### Type Definition
```typescript
type RetryOptions = {
retries?: number;
retryDelays?: number[];
shouldRetry?: (error: unknown, attemptNumber: number) => boolean;
jitter?: number; // 0–1
};
```
```
--------------------------------
### React MediaDrop with XHR Upload Transport
Source: https://github.com/autorender/react-mediadrop/blob/main/README.md
Configure useMediaDrop with an XHR upload transport for handling file uploads. Specify the endpoint, concurrency, and retries.
```ts
import { useMediaDrop } from "react-mediadrop";
import { createXhrUploadTransport } from "react-mediadrop/xhr-upload";
const { files, uploadAll } = useMediaDrop({
transport: createXhrUploadTransport({ endpoint: "/api/upload" }),
concurrency: 3,
retries: 2,
});
```
--------------------------------
### createXhrUploadTransport
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/xhr-upload.mdx
Creates an upload transport that sends files using XMLHttpRequest. This is useful for applications that need to display upload progress, as XMLHttpRequest provides a reliable `onprogress` event across browsers, unlike the Fetch API.
```APIDOC
## createXhrUploadTransport
### Description
Creates an upload transport that sends files using `XMLHttpRequest`. This is useful for applications that need to display upload progress, as `XMLHttpRequest` provides a reliable `onprogress` event across browsers, unlike the Fetch API.
### Method Signature
`createXhrUploadTransport(options: XhrUploadTransportOptions): UploadTransport`
### Options
| Option | Type | Default | Notes |
| --- | --- | --- | --- |
| `endpoint` | `string | (file) => string` | — required | Computed per file, e.g. for a per-file presigned URL you already fetched. |
| `method` | `string` | `"POST"` | |
| `fieldName` | `string` | `"file"` | Ignored when `formData: false`. |
| `fields` | `object | (file) => object` | — | Extra multipart fields. Ignored when `formData: false`. |
| `headers` | `object | (file) => object` | — | |
| `withCredentials` | `boolean` | `false` | |
| `formData` | `boolean` | `true` | `false` sends the raw file body. |
| `isSuccessStatus` | `(status) => boolean` | `200–299` | |
| `stallTimeoutMs` | `number` | `0` (disabled) | Abort and reject if no upload progress happens for this long — a *stall* timeout (reset on every progress tick), not a flat total-duration one, so a large file on a slow-but-healthy connection is never falsely aborted. |
### Usage Example
```ts
import { useMediaDrop } from "react-mediadrop";
import { createXhrUploadTransport } from "react-mediadrop/xhr-upload";
const transport = createXhrUploadTransport({
endpoint: "/api/upload", // or (file) => `/api/upload/${file.id}` for a per-file URL
fields: { folder: "avatars" }, // extra multipart fields
});
const { files } = useMediaDrop({ transport, concurrency: 3, retries: 2 });
```
### Notes
- This transport is intended for generic REST-ish endpoints that you control.
- It defaults to `multipart/form-data` but can send the raw file bytes if `formData: false`.
- It does not include retry logic or concurrency control; these are handled by the queue (e.g., `useMediaDrop`).
- It does not have a flat request timeout, only a `stallTimeoutMs` to detect lack of progress.
- Uploads are not resumable; failed or canceled uploads restart from the beginning.
```
--------------------------------
### Accessing MediaDrop Engine State
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/guides/core-concepts.mdx
Retrieve the current state of the media drop engine, which includes an array of files. This is useful for external state management or debugging.
```typescript
engine.getState(); // { files: MediaDropFile[] }
```
```typescript
engine.subscribe(listener); // full-state subscription
```
```typescript
engine.subscribe(selector, listener); // fires only when selector's result changes
```
--------------------------------
### MediaDropUploadSessionStore Interface
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/guides/upload.mdx
Defines the interface for storing upload session metadata, such as upload IDs and byte offsets, for resumable transports.
```typescript
type MediaDropUploadSessionStore = {
get(key: string): Promise;
set(key: string, value: unknown): Promise;
remove(key: string): Promise;
};
```
--------------------------------
### MediaDropRestrictions Type
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/types.mdx
Defines the constraints that can be applied to files during the drop process, such as size limits and accepted file types.
```APIDOC
## MediaDropRestrictions Type
### Description
Defines the constraints that can be applied to files during the drop process, such as size limits and accepted file types.
### Type Definition
```typescript
type MediaDropRestrictions = {
maxFiles?: number;
minSize?: number; // bytes
maxSize?: number; // bytes
accept?: string[] | string; // mime types, wildcards, or extensions
};
```
```
--------------------------------
### MediaDropUploadSessionStore Type
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/types.mdx
An interface for storing and retrieving upload session data, used for implementing custom resumable transports.
```APIDOC
## MediaDropUploadSessionStore Type
### Description
An interface for storing and retrieving upload session data, used for implementing custom resumable transports.
### Type Definition
```typescript
type MediaDropUploadSessionStore = {
get(key: string): Promise;
set(key: string, value: unknown): Promise;
remove(key: string): Promise;
};
```
```
--------------------------------
### Retry Options Type Definition
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/guides/upload.mdx
Defines the configuration options for the retry engine, including the number of retries, delay strategy, custom retry conditions, and jitter for spreading retries.
```typescript
type RetryOptions = {
retries?: number; // retries after the first attempt. Default 0.
retryDelays?: number[]; // backoff per retry; last value repeats if exhausted.
shouldRetry?: (error: unknown, attemptNumber: number) => boolean; // default: defaultShouldRetry
jitter?: number; // 0–1, randomizes each delay by up to this fraction. Default 0.
};
```
--------------------------------
### Set Max Files in React MediaDrop
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/examples/(basics)/max-files.mdx
Use the `restrictions.maxFiles` option to cap the number of files a dropzone accepts. This limit is evaluated against the entire file list, not per individual upload batch.
```tsx
import { MediaDropzone } from 'react-mediadrop';
function MyDropzone() {
return (
);
}
```
--------------------------------
### MediaDropFile Type
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/types.mdx
Defines the structure of a file object managed by react-mediadrop, including its metadata, status, and upload-related fields.
```typescript
type MediaDropFile = {
id: string;
file: File;
name: string;
size: number;
type: string;
lastModified?: number;
status: "idle" | "accepted" | "rejected";
errors: MediaDropError[];
// Upload fields, only set once an upload is requested:
uploadStatus?: "queued" | "uploading" | "done" | "error" | "canceled";
progress?: { loaded: number; total: number | null };
uploadError?: MediaDropError;
uploadResult?: unknown;
uploadAttempts?: number;
};
```
--------------------------------
### Understanding Drag State in React Media Drop
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/guides/core-concepts.mdx
Examine the different states of a drag operation within the dropzone. `isDragActive` indicates an active drag, `isDragAccept` suggests the payload is acceptable, and `isDragReject` indicates it is not. Note that `isDragAccept` and `isDragReject` rely on MIME types for accurate mid-drag evaluation.
```typescript
type DragState = {
isDragActive: boolean; // a drag payload is over this dropzone right now
isDragAccept: boolean; // best-effort: payload looks acceptable
isDragReject: boolean; // best-effort: payload looks unacceptable
};
```
--------------------------------
### useMediaDrop Hook Signature
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/api-reference/use-media-drop.mdx
Defines the signature of the useMediaDrop hook, including its optional configuration options for restrictions, validation, interaction control, and upload transport.
```typescript
function useMediaDrop(options?: {
restrictions?: MediaDropRestrictions;
validator?: MediaDropValidator;
noClick?: boolean; // disable click-to-open on the root
noKeyboard?: boolean; // disable Space/Enter-to-open and focus tracking
noDrag?: boolean; // disable the root's drag/drop handling
transport?: UploadTransport; // opt into upload — see below
concurrency?: number; // max uploads in flight at once. Default 1.
retries?: number; // retries after the first attempt. Default 0.
retryDelays?: number[]; // backoff per retry.
cancelGraceMs?: number; // force-free a slot after cancel. Default 5000.
}): UseMediaDropResult;
```
--------------------------------
### MediaDropFile Upload Fields Type Definition
Source: https://github.com/autorender/react-mediadrop/blob/main/apps/docs/docs/guides/upload.mdx
Defines the structure for upload-related properties within a MediaDropFile object. Includes upload status, progress, error details, and result information.
```typescript
type MediaDropFile = {
// ...status, errors, etc. — unchanged from Core...
uploadStatus?: "queued" | "uploading" | "done" | "error" | "canceled";
progress?: { loaded: number; total: number | null };
uploadError?: MediaDropError; // code: "upload-error", present after a failed attempt
uploadResult?: unknown; // whatever the transport resolved with — opaque to the engine
uploadAttempts?: number; // 1-indexed, for the current/last upload run
};
```