Next.js Discord

Discord Forum

SyntaxError: await is only valid in async functions and the top level bodies of modules

Unanswered
Siricid woodwasp posted this in #help-forum
Open in Discord
Original message was deleted.

11 Replies

Siricid woodwasp
can someone please help what im doing wrong?
can you show the code where you using the handler function?
Siricid woodwasp
"use client";

import { useState } from "react";
import { handler } from "./action";

export function Form() {
  const [file, setFile] = useState<File | null>(null);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) setFile(file);
  };
  async function handleSubmit() {
    if (!file) return;

    const form = new FormData();

    form.append("fileUpload", file);
    await handler(form);
  }

  return (
    <>
      <form>
        <input
          name="file"
          type="file"
          accept="image/png, image/jpeg"
          onChange={handleFileChange}
        />
      </form>
      <button onClick={handleSubmit}>Submit</button>
    </>
  );
}
try
async function handler(formData: FormData) {
  console.log(formData.get("fileUpload"));
  const upload = new Upload({
    client: new S3Client({}),
    params: {
      Key: crypto.randomUUID(),
      Bucket: Bucket.bucket.bucketName,
      Body: formData.get("fileUpload")!,
      // ContentType: formData.get("file"),
      ACL: "public-read",
    },
  });

  upload.on("httpUploadProgress", (progress) => {
    console.log(progress);
    1;
  });

  await upload.done();
}
Siricid woodwasp
doesnt work
complete error is this
 SyntaxError: await is only valid in async functions and the top level bodies of modules
    at __webpack_require__ (/home/madmax/sst-stuff/final-nub/packages/web/.next/server/webpack-runtime.js:33:42)
    at __webpack_require__ (/home/madmax/sst-stuff/final-nub/packages/web/.next/server/webpack-runtime.js:33:42)
    at eval (./src/app/action.ts:11:73)
    at (action-browser)/./src/app/action.ts (/home/madmax/sst-stuff/final-nub/packages/web/.next/server/app/page.js:356:1)
    at Function.__webpack_require__ (/home/madmax/sst-stuff/final-nub/packages/web/.next/server/webpack-runtime.js:33:42)
but its clearly async
try to pass the handler function from server component to the Form component
the Form component can still use the import one
Spectacled bear
@Ray how do I do that?