Next.js Discord

Discord Forum

Server action cant accept File as parameters? How to work around it?

Answered
English Spot posted this in #help-forum
Open in Discord
English SpotOP
When i try to pass an object with one of the key is File it throws this error
react-dom.development.js:8585 Uncaught Error: Only plain objects, and a few built-ins, can be passed to Server Actions. Classes or null prototypes are not supported.
Answered by joulev
const form = new FormData();
form.append("image", file);
await action(form);

"use server";

async function action(form: FormData) {
  const image = form.get("image");
}
View full answer

6 Replies

English SpotOP
type BasicSetting = {
    username: string;
    name: string;
    avatar?: File | undefined;
}

'use client'
  const onSubmit = handleSubmit(async (data) => {
    try {
      setIsLoading(true);
      await updateUserProfile(data);
    } catch (error) {
      console.log(error, ' something went wrong');
    }
  });

'use server'
export const updateUserProfile = async (userData: BasicSetting) => {
  //my code here
}}

If avatar is undefined it works just fine somehow without throwing the error
@joulev use `FormData`
English SpotOP
what do you mean, i dont really get it?
@English Spot what do you mean, i dont really get it?
use the FormData format to send data to server actions
const form = new FormData();
form.append("image", file);
await action(form);

"use server";

async function action(form: FormData) {
  const image = form.get("image");
}
Answer
English SpotOP
Okay, thanks this solved it!