I have an issue with the fetch function.
I have a long form with two of the fields being file uploads, my backend in fastify handles it via formData multipart. when I try to pass the formData to the server component I get the error.
form.tsx:
const dateParser = (object: any, dateFields: string[]) => {
const parsedObject = { ...object };
for (const fieldName of dateFields) {
if (parsedObject[fieldName] instanceof Date) {
parsedObject[fieldName] = parsedObject[fieldName]
.toISOString()
.substring(0, 10);
}
}
return parsedObject;
};
const form = useForm<TEscortSchema>({
resolver: zodResolver(escortSchema, { errorMap: customErrorMap }),
defaultValues: isEdit ? parsedEntity : defaultFormValues,
});
const {
reset,
getValues,
handleSubmit,
control,
formState: { isSubmitting, errors },
} = form;
const onSubmit = async (values: TEscortSchema) => {
try {
const formData = new FormData();
if (traineeId && !isEdit) {
formData.append("traineeId", traineeId);
}
const parsedValues = dateParser(values, dateFields);
(Object.keys(parsedValues) as Array<keyof TEscortSchema>).forEach(
(key) => {
if (values[key] instanceof FileList && values[key].length > 0) {
let file = values[key][0];
file = renameFile(file, key);
formData.append(key, file);
} else if (values[key]) {
formData.append(key, values[key]);
}
},
);
for (const key of formData.keys()) {
console.log(key, formData.get(key));
}
const URI = isEdit ? `/api/escorts/${escortId}` : `/api/escorts`;
const res = await makeFormDataRequest({URI, method: isEdit ? "PUT" : "POST", body: formData})
if (!res.ok) {
toast.error(hebrewTranslations["catch_error_toast"]);
} else if (res.status === 200) {
toast.success(
`${
hebrewTranslations[
isEdit ? "escortEditSuccess" : "escortAddSuccess"
]
}`,
);
router.push(`/trainee/${traineeId}`);
reset();
}
} catch (e) {
reset(values);
toast.error(hebrewTranslations["catch_error_toast"]);
}
};
api.ts:
const makeFormDataRequest = async ({
URI,
method,
body,
}: {
URI: string;
method: string;
body: FormData;
}) => {
const BASE_URL = `${process.env.NEXT_PUBLIC_SERVER_URL}/coach`;
const authToken = cookies().get("auth-token")?.value;
try {
const res = await fetch(`${BASE_URL}/${URI}`, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
},
method,
body,
});
const data = await res.json();
return data;
} catch (err) {
return NextResponse.json(
{ message: err instanceof Error ? err.message : err },
{ status: 500 },
);
}
};
getting:
⨯ Error: Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported.
at stringify (<anonymous>)
how can I transfer this formData to a server component ? it needs to be in a server for the cookies