Question: React component error import React, { useState } from 'react'; const DataForm = ( { addNewItem } ) = > { const [ name ,

React component error
import React, { useState } from 'react';
const DataForm =({ addNewItem })=>{
const [name, setName]= useState('');
const [brand, setBrand]= useState('');
const [price, setPrice]= useState('');
const [error, setError]= useState(null);
const [success, setSuccess]= useState(false);
const handleSubmit = async (e)=>{
e.preventDefault();
// Client-side validation
if (!name ||!brand ||!price){
setError('All fields are required');
return;
}
const priceNumber = parseFloat(price);
if (isNaN(priceNumber)){
setError('Price must be a valid number');
return;
}
try {
const response = await fetch('url goes here', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name, brand, price: priceNumber }),
});
const data = await response.json();
if (data.success){
setSuccess(true);
addNewItem(data.newItem);
setName('');
setBrand('');
setPrice('');
} else {
setError('Failed to add the item');
}
} catch (err){
setError('An error occurred');
}
};
return (
{error}Item added successfully!
React component error import React, { useState }

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!