Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: onFileUploadComplete #1175

Merged
merged 2 commits into from
Apr 8, 2025

Conversation

Roilan
Copy link

@Roilan Roilan commented Apr 3, 2025

I was speaking with Mark about if the upload progress is available on React Native. He mentioned implementation issues with XHR referencing expo/expo#28269.

I asked if there was a callback or hook when a file is uploaded vs all files uploaded. Having this would allow us to "fake" upload progress by saying "Uploading file 1 out of 5", etc.

This PR starts the initial callback functionality for React. It's working on my local pnpm link setup as expected. The types are iffy since I'm unsure how all the types work in the uploadthing repo, so I'd love some help with that. I'm open to changing anything that fits the general public vs just my usecase.

Summary by CodeRabbit

  • New Features
    • Added a callback option to handle file upload completion events, allowing developers to easily execute custom logic when an upload finishes.
    • Enhanced the upload process by seamlessly integrating this callback for improved user feedback and control.

Copy link

changeset-bot bot commented Apr 3, 2025

⚠️ No Changeset found

Latest commit: 6b92ca0

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Apr 3, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
docs-uploadthing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 4, 2025 8:47pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
legacy-docs-uploadthing ⬜️ Ignored (Inspect) Visit Preview Apr 4, 2025 8:47pm

Copy link
Contributor

coderabbitai bot commented Apr 3, 2025

Walkthrough

The changes add a new optional callback, onFileUploadComplete, to several parts of the upload process. This callback is now imported and used in the React component, its types, and in the internal upload functions. The modifications allow the upload process to trigger custom logic after a file is successfully uploaded, without altering the existing control flow.

Changes

File Path(s) Summary
packages/react/src/{components/button.tsx, types.ts, use-uploadthing.ts} Added onFileUploadComplete callback support in the component, type definitions, and internal hook by integrating it into the upload initiation and parameter list.
packages/uploadthing/src/{_internal/upload-browser.ts, types.ts} Introduced onFileUploadComplete as an optional callback in the upload function and extended its type definitions, updating method signatures to pass the callback when uploads complete.

Sequence Diagram(s)

sequenceDiagram
    participant U as UploadButton
    participant S as startUpload
    participant H as useUploadThingInternal
    participant F as uploadFile
    participant C as onFileUploadComplete Callback

    U->>S: Initiates upload with callback
    S->>H: Calls uploadFiles with onFileUploadComplete
    H->>F: Triggers file upload, passing callback
    F-->>H: Returns file upload result
    H->>C: Invokes onFileUploadComplete with file data
Loading

Possibly related PRs

  • chore: add server uploads to pg #1055: Introduces similar upload completion callbacks and modifications in components and functions, aligning with the integration of onFileUploadComplete in this PR.

Suggested labels

📚 documentation, examples

Suggested reviewers

  • markflorkowski

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

Scope: all 3 workspace projects
Progress: resolved 0, reused 0, downloaded 1, added 0
Progress: resolved 18, reused 0, downloaded 18, added 0
/tmp/eslint/packages/uploadthing:
 ERR_PNPM_WORKSPACE_PKG_NOT_FOUND  In packages/uploadthing: "@uploadthing/mime-types@workspace:*" is in the dependencies but no package named "@uploadthing/mime-types" is present in the workspace

This error happened while installing a direct dependency of /tmp/eslint/packages/uploadthing

Packages found in the workspace:

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🔭 Outside diff range comments (1)
packages/uploadthing/src/client.ts (1)

151-169: 🛠️ Refactor suggestion

Update the controllable upload to support the onFileUploadComplete callback

The controllableUpload function should also trigger the onFileUploadComplete callback when a file upload completes. This ensures consistent behavior between the two upload methods.

Update the upload promise resolution to call the callback:

void Micro.runPromiseExit(uploadEffect(file, p), {
  signal: deferred.ac.signal,
})
  .then((result) => {
    if (result._tag === "Success") {
+     opts.onFileUploadComplete?.(result.value, i, presigneds.length);
      return deferred.resolve(result.value);
    } else if (result.cause._tag === "Interrupt") {
      throw new UploadPausedError();
    }
    throw Micro.causeSquash(result.cause);
  })
  .catch((err) => {
    if (err instanceof UploadPausedError) return;
    deferred.reject(err);
  });
🧹 Nitpick comments (2)
packages/react/src/types.ts (1)

56-63: New callback for individual file upload completion tracking

The addition of onFileUploadComplete callback is a nice enhancement that allows tracking individual file uploads. This will be useful for showing progress like "Uploading file X out of Y."

However, the uploadResponse parameter is typed as any, which loses type safety. Consider using a more specific type like UploadPutResult<TServerOutput> to maintain type safety throughout the application.

onFileUploadComplete?: (
-  uploadResponse: any,
+  uploadResponse: UploadPutResult<TServerOutput>,
  index: number,
  total: number,
) => void;
packages/uploadthing/src/client.ts (1)

256-262: Document the new callback in JSDoc comments

The new onFileUploadComplete callback lacks documentation explaining its purpose and parameters. Adding JSDoc comments would help users understand what this callback does and when it's called.

Add JSDoc comments for the new parameter:

> & {
+  /**
+   * Callback that is called when a single file upload completes.
+   * This can be used to implement a "fake" upload progress indicator
+   * (e.g., "Uploading file 1 out of 5").
+   * 
+   * @param uploadResponse The response from the completed file upload
+   * @param index The index of the file that was uploaded (0-based)
+   * @param total The total number of files being uploaded
+   */
  onFileUploadComplete?: (
    uploadResponse: any,
    index: number,
    total: number,
  ) => void;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cff049c and b678750.

📒 Files selected for processing (5)
  • packages/react/src/components/button.tsx (2 hunks)
  • packages/react/src/types.ts (1 hunks)
  • packages/react/src/use-uploadthing.ts (1 hunks)
  • packages/uploadthing/src/_internal/upload-browser.ts (3 hunks)
  • packages/uploadthing/src/client.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
packages/uploadthing/src/_internal/upload-browser.ts (1)
packages/uploadthing/src/_internal/types.ts (1)
  • UploadPutResult (188-202)
🔇 Additional comments (5)
packages/react/src/use-uploadthing.ts (1)

90-94: LGTM - Properly passing the callback through the upload chain

The change correctly passes the new onFileUploadComplete callback from the hook props to the uploadFiles function, maintaining the callback chain.

packages/react/src/components/button.tsx (2)

6-10: LGTM - Clean up of import statement

The replacement of commented-out imports with proper typed imports improves code clarity and maintainability.


119-121: LGTM - Proper implementation of the new callback

The implementation correctly passes the callback parameters to the user-provided function. This maintains the contract defined in the type definition.

packages/uploadthing/src/_internal/upload-browser.ts (2)

110-113: Type definition aligns with implementation

The type definition for onFileUploadComplete correctly specifies that it receives a UploadPutResult<TServerOutput> as its parameter, which is what the implementation provides.


139-139: LGTM - Efficient implementation using Micro's tap operator

The use of Micro.tap is an elegant way to handle the callback without affecting the main data flow. This is a clean functional programming approach.

Comment on lines 256 to 262
> & {
onFileUploadComplete?: (
uploadResponse: any,
index: number,
total: number,
) => void;
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Implementation incomplete: callback needs to be passed to uploadFilesInternal

The onFileUploadComplete callback has been added to the type definition but is not being passed to the uploadFilesInternal function where it should be utilized. Without this, the callback won't be called when a file upload completes.

Add the callback to the options passed to uploadFilesInternal:

return uploadFilesInternal<TRouter, TEndpoint>(endpoint, {
  ...opts,
  skipPolling: {} as never, // Remove in a future version, it's type right not is an ErrorMessage<T> to help migrations.
  url: resolveMaybeUrlArg(initOpts?.url),
  package: initOpts?.package ?? "uploadthing/client",
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  input: (opts as any).input as inferEndpointInput<TRouter[TEndpoint]>,
+ onFileUploadComplete: opts.onFileUploadComplete,
})
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
> & {
onFileUploadComplete?: (
uploadResponse: any,
index: number,
total: number,
) => void;
},
return uploadFilesInternal<TRouter, TEndpoint>(endpoint, {
...opts,
skipPolling: {} as never, // Remove in a future version, it's type right not is an ErrorMessage<T> to help migrations.
url: resolveMaybeUrlArg(initOpts?.url),
package: initOpts?.package ?? "uploadthing/client",
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
input: (opts as any).input as inferEndpointInput<TRouter[TEndpoint]>,
onFileUploadComplete: opts.onFileUploadComplete,
})

🛠️ Refactor suggestion

Add the same callback to the controllableUpload function for consistency

The onFileUploadComplete callback has been added to the typedUploadFiles function but not to the controllableUpload function. According to the PR summary, this callback should be available for both functions to ensure consistent behavior across different upload methods.

Additionally, the uploadResponse parameter is typed as any, which could lead to type-safety issues. Consider using a more specific type that matches the actual upload response structure.

const controllableUpload = async <
  TEndpoint extends keyof TRouter,
  TServerOutput = inferEndpointOutput<TRouter[TEndpoint]>,
>(
  slug: EndpointArg<TRouter, TEndpoint>,
  opts: Omit<
    CreateUploadOptions<TRouter[TEndpoint]>,
    keyof GenerateUploaderOptions
+ > & {
+   onFileUploadComplete?: (
+     uploadResponse: ClientUploadedFileData<TServerOutput>,
+     index: number,
+     total: number,
+   ) => void;
  },
) => {

Also, in the typedUploadFiles function, consider using a more specific type instead of any:

onFileUploadComplete?: (
-  uploadResponse: any,
+  uploadResponse: ClientUploadedFileData<inferEndpointOutput<TRouter[TEndpoint]>>,
  index: number,
  total: number,
) => void;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
> & {
onFileUploadComplete?: (
uploadResponse: any,
index: number,
total: number,
) => void;
},
// Updated controllableUpload function with onFileUploadComplete added to opts
const controllableUpload = async <
TEndpoint extends keyof TRouter,
TServerOutput = inferEndpointOutput<TRouter[TEndpoint]>,
>(
slug: EndpointArg<TRouter, TEndpoint>,
opts: Omit<
CreateUploadOptions<TRouter[TEndpoint]>,
keyof GenerateUploaderOptions
> & {
onFileUploadComplete?: (
uploadResponse: ClientUploadedFileData<TServerOutput>,
index: number,
total: number,
) => void;
},
) => {
// function body
};
// Updated onFileUploadComplete callback signature in typedUploadFiles function
// (Assuming the following type is part of the options for typedUploadFiles)
type TypedUploadFilesOptions = {
// ... other options
onFileUploadComplete?: (
uploadResponse: ClientUploadedFileData<inferEndpointOutput<TRouter[TEndpoint]>>,
index: number,
total: number,
) => void;
// ... other options
};

Comment on lines 59 to 63
onFileUploadComplete?: (
uploadResponse: any,
index: number,
total: number,
) => void;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a fan of this API. I'm currently blocked on making changes to the progress callback since we chose to use positional arguments there instead of an object 😓

Suggested change
onFileUploadComplete?: (
uploadResponse: any,
index: number,
total: number,
) => void;
onFileUploadComplete?: (_: {
uploadResponse: any, // <-- also, this shouldn't be any
index: number,
total: number,
}) => void;

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/uploadthing/src/types.ts (2)

12-12: Consider using a relative import path for ClientUploadedFileData

The file is importing ClientUploadedFileData from "./types" but also re-exporting it from "./_internal/shared-schemas" on line 25. This could potentially lead to circular dependencies. Consider importing it directly from "./_internal/shared-schemas" for clarity.

- import type { ClientUploadedFileData } from "./types";
+ import type { ClientUploadedFileData } from "./_internal/shared-schemas";

131-146: Consider enhancing the callback with index and total parameters

The onFileUploadComplete callback is well-documented, but it doesn't include index and total properties that would make it easier to implement a "Uploading file X out of Y" progress indicator, which was one of the primary needs mentioned in the PR description.

  onFileUploadComplete?:
    | ((_: {
        /**
         * The response from the upload
         */
        fileData: ClientUploadedFileData<inferEndpointOutput<TFileRoute>>;
        /**
         * The file object that was uploaded
         */
        file: File;
        /**
         * All the files that are in this upload
         */
        files: File[];
+       /**
+        * The index of the current file in the upload queue (0-based)
+        */
+       index: number;
+       /**
+        * The total number of files in the upload queue
+        */
+       total: number;
      }) => void)
    | undefined;
packages/react/src/types.ts (1)

56-59: Clarify interaction with awaitServerData option

The documentation for onClientUploadComplete (line 118) mentions that it's called after the serverside onUploadComplete callback has finished if RouteOptions.awaitServerData is true. It would be helpful to clarify in the documentation for onFileUploadComplete how it interacts with the awaitServerData option.

  /**
   * Called when a file upload is completed
+  * @remarks If `RouteOptions.awaitServerData` is `true`, this will be
+  * called after the serverside processing for this file has finished
   */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b678750 and 6b92ca0.

📒 Files selected for processing (4)
  • packages/react/src/components/button.tsx (2 hunks)
  • packages/react/src/types.ts (1 hunks)
  • packages/uploadthing/src/_internal/upload-browser.ts (3 hunks)
  • packages/uploadthing/src/types.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/react/src/components/button.tsx
  • packages/uploadthing/src/_internal/upload-browser.ts
🧰 Additional context used
🧬 Code Definitions (2)
packages/react/src/types.ts (1)
packages/uploadthing/src/types.ts (1)
  • ClientUploadedFileData (25-25)
packages/uploadthing/src/types.ts (1)
packages/uploadthing/src/_internal/shared-schemas.ts (1)
  • ClientUploadedFileData (96-101)
🔇 Additional comments (1)
packages/react/src/types.ts (1)

59-74: Consider enhancing the callback with index and total parameters

The onFileUploadComplete callback should include index and total properties to make it easier to implement a "Uploading file X out of Y" progress indicator, which was specifically mentioned in the PR description. This matches a previous comment from juliusmarminge who had similar feedback.

  onFileUploadComplete?:
    | ((_: {
        /**
         * The response from the upload
         */
        fileData: ClientUploadedFileData<TServerOutput>;
        /**
         * The file object that was uploaded
         */
        file: File;
        /**
         * All the files that are in this upload
         */
        files: File[];
+       /**
+        * The index of the current file in the upload queue (0-based)
+        */
+       index: number;
+       /**
+        * The total number of files in the upload queue
+        */
+       total: number;
      }) => void)
    | undefined;

@Roilan
Copy link
Author

Roilan commented Apr 5, 2025

@juliusmarminge You're the goat. Like I said, this was to fit my particular use case, but I'm glad you've updated it to fit the general public. What is the process of getting this merged? It's something I'm waiting on to continue developing our RN app.

@markflorkowski
Copy link
Collaborator

@Roilan this pr has sparked a bunch of conversation internally around what these APIs should look like 😅

Will continue to follow up next week

@juliusmarminge juliusmarminge added the release canary Trigger a canary release to npm label Apr 5, 2025
@juliusmarminge
Copy link
Member

I'll release a canary if that helps unblock you.

We will support this use case but thinking about the exact API on a broader plane

@Roilan
Copy link
Author

Roilan commented Apr 6, 2025

@markflorkowski @juliusmarminge Haha, sorry. I'm surprised nobody has needed this before. The changes that Julius has made should unblock me. I'm okay with whatever the API for the canary release is. I can make adjustments in the future with what the official API ends up being. However, I just want to confirm that no other changes are needed "useImageUploader" in Expo since that's what I need it for.

@markflorkowski markflorkowski changed the base branch from main to roilan/onfileuploadcomplete April 8, 2025 16:47
@markflorkowski
Copy link
Collaborator

merging into unforked branch to make canary

@markflorkowski markflorkowski merged commit 551afc4 into pingdotgg:roilan/onfileuploadcomplete Apr 8, 2025
20 of 21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
release canary Trigger a canary release to npm @uploadthing/react
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants