Question: Here's the DataForm code for reference. Thank you. import React, { useState } from 'react'; const DataForm = ( { addNewItem, updateItem, deleteItem } )

Here's the DataForm code for reference. Thank you.
import React, { useState } from 'react';
const DataForm =({ addNewItem, updateItem, deleteItem })=>{
const [name, setName]= useState('');
const [brand, setBrand]= useState('');
const [price, setPrice]= useState('');
const [image, setImage]= useState(null);
const [error, setError]= useState(null);
const [success, setSuccess]= useState(false);
const handleImageChange =(e)=>{
setImage(e.target.files[0]);
};
const handleSubmit = async (e)=>{
e.preventDefault();
if (!name.trim()||!brand.trim()||!price.trim()||!image){
setError('All fields are required, including an image.');
setSuccess(false);
return;
}
const formData = new FormData();
formData.append('name', name);
formData.append('brand', brand);
formData.append('price', price);
formData.append('image', image);
try {
const response = await fetch('My URL here', {
method: 'POST',
body: formData,
});
const data = await response.json();
if (data.success){
setSuccess(true);
addNewItem(data.newItem);
setName('');
setBrand('');
setPrice('');
setImage(null);
} else {
setError(data.message || 'Failed to add the item.');
setSuccess(false);
}
} catch (err){
setError('An error occurred while submitting the form.');
setSuccess(false);
}
};
return (

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!