Untitled conversation
- User
{ "food": "CHICKEN BREAST", "weight": 400, "nutrients": { "protein": 81.6, "fats": 18.32, "carbohydrates": 4.24, "calories": 660 }, "servingSize": 284 }-- this is the response on my backend. i want to display the serving size on my front end. what am i missing? -import { useState, useEffect } from "react";
const FoodDetails = ({ nutrition, onBack, onAdd }) => { const [weight, setWeight] = useState(nutrition.weight); const [servingSize, setServingSize] = useState(nutrition.servingSize); const [foodData, setFoodData] = useState(nutrition); const [loading, setLoading] = useState(false); const [error, setError] = useState("");
// Auto-refresh nutrients when weight changes useEffect(() => { const fetchUpdatedNutrition = async () => { if (!foodData.food || isNaN(weight)) return; setLoading(true); try { const url = `http://localhost:3000/search?food=${encodeURIComponent(foodData.food)}&weight=${weight}`; const response = await fetch(url); if (!response.ok) throw new Error("Failed to update nutrition data"); const data = await response.json(); setFoodData(data); setError(""); } catch (err) { setError("Could not update nutrition info"); } finally { setLoading(false); } }; fetchUpdatedNutrition(); }, [weight]); const handleAdd = () => { onAdd({ ...foodData, weight }); }; console.log("foodData:", foodData); return ( <div> <button onClick={onBack}>← Back to Search</button> <h3>{foodData.food}</h3> <label> Weight: <input type="number" value={weight} onChange={(e) => setWeight(parseFloat(e.target.value))} style={{ marginLeft: "8px" }} /> <span> g</span> </label> {loading ? ( <p>Loading updated nutrition...</p> ) : ( <div> <p><strong>Calories:</strong> {Math.round(foodData.nutrients.calories)} kcal</p> <p><strong>Carbs:</strong> {Math.round(foodData.nutrients.carbohydrates)} g</p> <p><strong>Protein:</strong> {Math.round(foodData.nutrients.protein)} g</p> <p><strong>Fats:</strong> {Math.round(foodData.nutrients.fats)} g</p> </div> )} {error && <p style={{ color: 'red' }}>{error}</p>} <button onClick={handleAdd} style={{ marginTop: "10px" }}> ➕ Add Food </button> </div> );};
export default FoodDetails;
Assistant
To display the serving size on your front end, you need to ensure that the component renders the
servingSizevalue directly from thefoodDataobject, rather than relying on an outdated or unnecessary local state.
✅ What's Missing?
You're currently initializing a local state variable:
const [servingSize, setServingSize] = useState(nutrition.servingSize);However, this value is not being used anywhere in the JSX, and more importantly, it's not being updated when the
foodDatachanges after an API call. This leads to stale or incorrect serving size data being potentially displayed.
✅ Solution: Use
foodData.servingSizeDirectlyInstead of keeping a separate state for
servingSize, use the value directly from thefoodDataobject, which is updated whenever the backend returns new data.
✅ Implementation
- Remove the unnecessary state:
// ❌ Remove this line: const [servingSize, setServingSize] = useState(nutrition.servingSize);- Display the serving size in the JSX:
You can add it right below the weight input or somewhere else in the UI:
<label> Weight: <input type="number" value={weight} onChange={(e) => setWeight(parseFloat(e.target.value))} style={{ marginLeft: "8px" }} /> <span> g</span> </label> {/* ✅ Add serving size here */} <p><strong>Serving Size:</strong> {foodData.servingSize || "N/A"} g</p>This will display the serving size in grams (assuming the backend returns it in grams).
✅ Optional: Format the Serving Size
If you'd like to make it more user-friendly, you could also round or format the number:
<p><strong>Serving Size:</strong> {Math.round(foodData.servingSize)} g</p>
✅ Bonus Tip: Ensure
servingSizeis in the API ResponseMake sure that your backend always includes the
servingSizefield in the response, even when recalculating nutrients based on weight. This ensures that the front end can consistently access and display it.
✅ Summary
What Was Wrong What to Fix Unused servingSizestateRemove the state and use foodData.servingSizeinsteadNo UI element for serving size Add a <p>or<label>to displayfoodData.servingSizePotential stale data Avoid keeping redundant state; rely on foodDatafor live updates
✅ Final Code Snippet (Updated Part)
<label> Weight: <input type="number" value={weight} onChange={(e) => setWeight(parseFloat(e.target.value))} style={{ marginLeft: "8px" }} /> <span> g</span> </label> <p><strong>Serving Size:</strong> {Math.round(foodData.servingSize)} g</p>This will ensure the serving size is correctly and dynamically displayed based on the latest data from the backend.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.