Question: Help needed with the below code: import React, { useState } from 'react'; const DataForm = ( { addNewItem } ) = > { const
Help needed with the below code:
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 handlelmageChange e
const file etarget.files;
if file
setImagefile; Save the selected file in 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.appendgear image;
setErrornull;
try
const response await fetchMy URL',
method: 'POST',
body: formData,
;
if response.ok
throw new ErrorServer error';
const data await response.json;
if datasuccess
setSuccesstrue;
addNewItemdatanewItem;
setName;
setBrand;
setPrice;
setImagenull;
document.getElementByIdfileInputvalue ; Reset file input
else
setErrordatamessage 'Failed to add the item';
setSuccessfalse;
catch err
setErrorAn error occurred while submitting the form';
setSuccessfalse;
;
const handleUpdate async itemld updatedData
try
const response await fetchMy URL$itemid
method: 'POST',
headers: 'ContentType': 'applicationjson
body: JSON.stringifyupdatedData
;
const data await response.json;
if datasuccess
updateltemdataupdatedItem;
setSuccesstrue;
else
setErrordatamessage 'Failed to update the item';
setSuccessfalse;
catch err
setErrorAn error occurred while updating the item';
setSuccessfalse;
;
const handleDelete async itemld
try
const response await fetchMy URL$itemId
method: 'DELETE',
;
const data await response.json;
if datasuccess
deleteltemitemld;
setSuccesstrue;
else
setErrordatamessage 'Failed to delete the item';
setSuccessfalse;
catch err
setErrorAn error occurred while deleting the item';
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
