I'm trying to build a form that can upload multiple images.
The images can be removed during the preview images.
For example, I upload the two images then, I try to click the remove button to remove one of two images that are working fine.
The problem is during I click the submit button suppose will post one image to API but there are still remaining two images post to API.
I'm using the React hook form, anyone knows what is the problems?
Here is the project links
https://codesandbox.io/s/boring-hermann-xrqbt
const methods = useFormContext();
const { control, watch, setValue, formState } = methods;
const [image, setImage] = useState([]);
function deleteFile(id) {
const s = image.filter((item, index) => item.id !== id);
setImage(s);
}
<div className="flex justify-center sm:justify-start flex-wrap -mx-16">
<Controller
name="images"
control={control}
render={({ field: { onChange, value } }) => (
<label
htmlFor="button-file"
className={clsx(
classes.productImageUpload,
"flex items-center justify-center relative w-128 h-128 rounded-16 mx-12 mb-24 overflow-hidden cursor-pointer shadow hover:shadow-lg"
)}
>
<input
accept="image/*"
className="hidden"
id="button-file"
type="file"
onChange={async (e) => {
function readFileAsync() {
return new Promise((resolve, reject) => {
const file = e.target.files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = () => {
resolve({
id: FuseUtils.generateGUID(),
url: `data:${file.type};base64,${btoa(reader.result)}`,
type: "image",
});
};
reader.onerror = reject;
reader.readAsBinaryString(file);
});
}
const newImage = await readFileAsync();
setImage([newImage, ...image]);
onChange([newImage, ...image]);
}}
/>
<Icon fontSize="large" color="action">
cloud_upload
</Icon>
</label>
)}
/>
<Controller
name="featuredImageId"
control={control}
defaultValue=""
render={({ field: { onChange, value } }) =>
image.map((media) => (
<div
onClick={() => onChange(media.id)}
onKeyDown={() => onChange(media.id)}
role="button"
tabIndex={0}
className={clsx(
classes.productImageItem,
"flex items-center justify-center relative w-128 h-128 rounded-16 mx-12 mb-24 overflow-hidden cursor-pointer outline-none shadow hover:shadow-lg",
media.id === value && "featured"
)}
key={media.id}
>
<Icon
className={classes.productImageFeaturedStar}
onClick={() => deleteFile(media.id)}
>
Delete
</Icon>
<img
className="max-w-none w-auto h-full"
src={media.url}
alt="product"
/>
</div>
))
}
/>
</div>;