Question: Having a couple of compile errors: import React, { useState } from 'react'; const DataForm = ( { addNewItem } ) = > { const
Having a couple of compile errors:
import React, useState from 'react';
const DataForm addNewItem
const name setName useState;
const brand setBrand useState;
const price setPrice useState;
const image setImage useStatenull; Added state for image file
const error setError useStatenull;
const success setSuccess useStatefalse;
const handleImageChange 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 fetchapi url',
method: 'POST',
body: formData,
;
if response.ok
throw new ErrorServer error';
const data await response.json;
if datasuccess
setSuccesstrue;
addNewItemdatanewItem;
Reset the form
setName;
setBrand;
setPrice;
setImagenull;
Reset file input
document.getElementByIdfileInputvalue ;
else
setErrordatamessage 'Failed to add the item';
setSuccessfalse;
catch err
setErrorAn error occurred while submitting the form';
setSuccessfalse;
;
const handleUpdate async itemId updatedData
try
const response await fetchapi url$itemId
method: 'POST',
body: JSON.stringifyupdatedData
;
const data await response.json;
if datasuccess
updateItemdataupdatedItem;
setSuccesstrue;
else
setErrordatamessage 'Failed to update the item';
setSuccessfalse;
catch err
setErrorAn error occurred while updating the item';
setSuccessfalse;
;
const handleDelete async itemId
try
const response await fetchapi url$itemId
method: 'DELETE',
;
const data await response.json;
if datasuccess
deleteItemitemId;
setSuccesstrue;
else
setErrordatamessage 'Failed to delete the item';
setSuccessfalse;
catch err
setErrorAn error occurred while deleting the item';
setSuccessfalse;
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
