How can i show progress bar using server action #80321
Unanswered
Faisal-vyomr
asked this question in
Help
Replies: 1 comment
-
Hi, I must confess I got a bit nerd-snipped by this. You could return a stream from the server action, and stream the progress. The stream code taken from: https://nextjs.org/docs/app/building-your-application/routing/route-handlers#streaming 'use server';
// https://developer.mozilla.org/docs/Web/API/ReadableStream#convert_async_iterator_to_stream
function iteratorToStream(iterator: any) {
return new ReadableStream({
async pull(controller) {
const { value, done } = await iterator.next();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
},
});
}
function sleep(time: number) {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
const encoder = new TextEncoder();
async function* makeIterator() {
yield encoder.encode('0%');
await sleep(200);
yield encoder.encode('25%');
await sleep(200);
yield encoder.encode('50%');
await sleep(200);
yield encoder.encode('75%');
await sleep(200);
yield encoder.encode('100%');
}
export async function streamer() {
const iterator = makeIterator();
const stream = iteratorToStream(iterator);
return stream;
} And a client component like so: 'use client';
import { useTransition, useState } from 'react';
import { streamer } from './stream';
export function Page() {
const [progress, setProgress] = useState('');
const [isPending, startTransition] = useTransition();
return (
<>
<div>Progress: {progress}</div>
<button
type="button"
className="bg-blue-400 text-white p-4 mt-4"
onClick={() => {
startTransition(async () => {
const state = await streamer();
const reader = state.getReader();
reader.read().then(function loop({ done, value }) {
if (done) return;
const update = new TextDecoder().decode(value);
setProgress(update);
return reader.read().then(loop);
});
});
}}
disabled={isPending}
>
Click me
</button>
</>
);
} Should do the trick! Screen.Recording.2025-06-09.at.16.01.15.mov |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
I am in a scenario where i was using server action to create an item with file(img or video etc). Now I want to show a progess bar of file upload. And I believe xmlHttpRequest wont work here.
Is there a way to show file upload progress bar while using server action
Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions