import React, { useState } from "react";
import { JoyDoc, getDefaultDocument } from "@joyfill/components";
function OnUploadAsyncExample() {
const [document, setDocument] = useState(() => {
const doc = getDefaultDocument();
const fields = [
{
_id: "galleryImages",
identifier: "galleryImages",
type: "image",
title: "Image Gallery",
value: [],
file: doc.files[0]._id,
multi: true,
},
];
doc.fields = fields;
doc.files[0].pages[0].fieldPositions.push({
_id: "galleryImages-position",
field: "galleryImages",
x: 0,
y: 0,
width: 1,
height: 1,
displayType: "original",
});
return doc;
});
const handleChange = (changelogs, updatedDoc) => {
setDocument(updatedDoc);
};
const handleUpload = async (params, fileUploads) => {
console.log("onUploadAsync triggered:", params, fileUploads);
const resultPromises = await fileUploads.map(async (fileUpload) => {
const dataUri = await getDataUriForFileUpload(fileUpload);
return uploadFileAsync(params.fieldIdentifier, dataUri);
});
return Promise.all(resultPromises)
.then((responses) => {
// Normalize response for different file types
const finalResponse = Array.isArray(responses[0])
? responses[0]
: responses;
console.log("Upload completed:", finalResponse);
return finalResponse;
})
.catch((error) => {
console.error("Upload error:", error);
if (error) return;
});
};
return (
<div>
<h1>onUploadAsync Example</h1>
<JoyDoc
doc={document}
onUploadAsync={handleUpload}
onChange={handleChange}
mode="edit"
width={816}
height={600}
/>
</div>
);
}
export default OnUploadAsyncExample;