I am taking the user input with handleInput
function and setting a useState()
hook variable named newProduct
but when ever I change the value of the input and add it to the newProduct
variable it is there with full information but when I console.log()
it in another function by which I am sending the data to backend, it is totally empty there.
here is the main code (the full code is so big so I am giving the main code of handleInput function and another function which sends the data to backend.)
newProduct useState variable :
const [newProduct, setNewProduct] = useState({
productId: props.Products.allProducts.length + 1,
name: '',
category: '',
price: '',
OriginalPrice: '',
description: '',
Mesurements: '',
Material: '',
Color: '',
Work: '',
StitchType: '',
Occasion: '',
printPattern: '',
SupplierSKU: '',
supplier: '',
CountryOfOrigin: '',
CareGuide: '',
});
handleInput Function:
let name, value;
const handleInput = (e) => {
name = e.target.name;
value = e.target.value;
setNewProduct({ ...newProduct, [name]: value });
console.log(newProduct) // here is totally filled with information which it should be.
}
Function which sends data to backend
const AddProducts = async (e) => {
console.log(newProduct); // it's values should be filled with information but it's totally empty.
e.preventDefault();
if (newProduct.name.length > 0) { // sending data to backend only if the newProduct have some information
try {
const res = await fetch('http://localhost:5000/addProduct', {
method: 'POST',
withCredentials: true,
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"productId": newProduct.productId,
"name": newProduct.name,
"category": newProduct.category,
"price": parseInt(newProduct.price),
"OriginalPrice": parseInt(newProduct.OriginalPrice),
"Images": productImages,
"description": newProduct.description,
"Mesurements": newProduct.Mesurements,
"Material": newProduct.Material,
"Color": newProduct.Color,
"ColorVariant": colorVariantInputs,
"Size": newProduct.sizeAvailable,
"Work": newProduct.Work,
"StitchType": newProduct.StitchType,
"Occasion": newProduct.Occasion,
"printPattern": newProduct.printPattern,
"SupplierSKU": newProduct.SupplierSKU,
"supplier": newProduct.supplier,
"CountryOfOrigin": newProduct.CountryOfOrigin,
"CareGuide": newProduct.CareGuide
})
}).then((response) => { return response.json() })
.then((data) => {
if (data) { }
})
} catch (error) { }
}
}
it's filled with information when I console.log
it in the handleInput
function:
it's empty when I console.log
it in the addProducts()
function: