Question: Hello - Please review the below code. I don't think that the state is being persisted. Picture also not working. ( : Requirements are: Complete
Hello Please review the below code. I don't think that the state is being persisted. Picture also not working. :
Requirements are:
Complete the post, put and delete requests using mongo to make the changes to the data persistent.
Pictures should work for the whole session.
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 useStatenull;
const error setError useStatenull;
const success setSuccess useStatefalse;
const handleImageChange e
const file etarget.files;
if file
setImagefile;
;
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;
Reset form
setName;
setBrand;
setPrice;
setImagenull;
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 fetchMy URL$itemId
method: 'PUT',
headers:
'ContentType': 'applicationjson
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 fetchMy 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;
;
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
