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 useStatenull;
const error setError useStatenull;
const success setSuccess useStatefalse;
const handleImageChange e
const file etarget.files;
if file
setImagefile; Save the file directly to the state
;
const handleSubmit async e
epreventDefault;
if name brand price image
setErrorAll fields, including an image, are required';
setSuccessfalse;
return;
const priceNumber parseFloatprice;
if isNaNpriceNumber
setErrorPrice must be a valid number';
setSuccessfalse;
return;
const formData new FormData;
formData.appendname name;
formData.appendbrand brand;
formData.appendprice priceNumber;
formData.appendimage image;
setErrornull;
try
const response await fetch Enter the url here
method: 'POST',
body: formData, Send FormData directly
;
const data await response.json;
if datasuccess
setSuccesstrue;
addNewItemdatanewItem;
setName;
setBrand;
setPrice;
setImagenull; Reset the image state
else
setErrorFailed to add the item';
setSuccessfalse;
catch err
setErrorAn error occurred while submitting the form';
setSuccessfalse;
;
return
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
