Question: Hello! So , I need to be able to add an image and edit and delete what the user has added. This code doesn't seem

Hello!
So, I need to be able to add an image and edit and delete what the user has added. This code doesn't seem to work:
Ok so i need to be able to add an image and edit and delete what the user has added. This is the code i have to let user add an image but it doesnt work:
import React, { useState } from 'react';
const DataForm =({ addNewItem })=>{
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)=>{
const file = e.target.files[0];
if (file){
setImage(file); // Save the file directly to the state
}
};
const handleSubmit = async (e)=>{
e.preventDefault();
if (!name ||!brand ||!price ||!image){
setError('All fields, including an image, are required');
setSuccess(false);
return;
}
const priceNumber = parseFloat(price);
if (isNaN(priceNumber)){
setError('Price must be a valid number');
setSuccess(false);
return;
}
const formData = new FormData();
formData.append('name', name);
formData.append('brand', brand);
formData.append('price', priceNumber);
formData.append('image', image);
setError(null);
try {
const response = await fetch(' Enter the url here ',{
method: 'POST',
body: formData, // Send FormData directly
});
const data = await response.json();
if (data.success){
setSuccess(true);
addNewItem(data.newItem);
setName('');
setBrand('');
setPrice('');
setImage(null); // Reset the image state
} else {
setError('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!