Issue with Passing Integer Values to Backend Server and Zod Validation Error
I’m encountering an issue with passing integer values from a React frontend to a backend server. Despite correctly passing integer values through a POST request, the Zod validation on the backend keeps returning an error stating ‘undefined’. I’m unsure why this validation is failing despite passing the appropriate data.
Here’s a snippet of my React frontend component responsible for handling the input and sending the data:
import React, { useState } from 'react';
export function CreateInput() {
const [name, setName] = useState("");
const [calorie, setCalorie] = useState("");
const [protein, setProtein] = useState("");
const [carbs, setCarbs] = useState("");
const inputStyle = {
marginBottom: '10px',
padding: '8px',
borderRadius: '5px',
border: '1px solid #ccc',
fontSize: '16px',
width: '250px',
boxSizing: 'border-box'
};
const buttonStyle = {
padding: '8px 16px',
borderRadius: '5px',
backgroundColor: '#4CAF50',
color: 'white',
border: 'none',
cursor: 'pointer',
fontSize: '16px'
};
const containerStyle = {
textAlign: 'center'
};
const handleAddFood = async () => {
// Validation to ensure fields are not empty
if (!name || !calorie || !protein || !carbs) {
alert("Please fill in all fields");
return;
}
// Convert the values to integers
const calorieInt = parseInt(calorie);
const proteinInt = parseInt(protein);
const carbsInt = parseInt(carbs);
// Check if parsing was successful
if (isNaN(calorieInt) || isNaN(proteinInt) || isNaN(carbsInt)) {
alert("Calorie, protein, and carbs must be numbers");
return;
}
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
try {
const response = await fetch('http://localhost:3000/inputfood', {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
date: formattedDateTime,
eat: {
name: name,
calorie: calorieInt,
protein: proteinInt,
carbs: carbsInt,
}
})
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
alert("Food Added");
} catch (error) {
console.error('Error adding food:', error);
alert("Failed to add food");
}
};
return (
<div style={containerStyle}>
<input style={inputStyle} type="text" placeholder="Input Name" onChange={(e) => setName(e.target.value)} /><br />
<input style={inputStyle} type="number" placeholder="Input Calorie cal" onChange={(e) => setCalorie(e.target.value)} /><br />
<input style={inputStyle} type="number" placeholder="Input Protein g" onChange={(e) => setProtein(e.target.value)} /><br />
<input style={inputStyle} type="number" placeholder="Input Carbs g" onChange={(e) => setCarbs(e.target.value)} /><br />
<button style={buttonStyle} onClick={handleAddFood}>Add Food</button>
</div>
);
}
Could anyone help me understand why the Zod validation on the backend is returning ‘undefined’ despite passing integer values correctly? I’d appreciate any insights or suggestions. Thank you!