Skip to content
TheChatArchiveThe Chat Archive
Qwenqwen3-235b-a22b· Alibaba (Qwen)Hugging Face LMArena Human Preference 140K

Untitled conversation

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-pro-preview-05-06’s answer.
  1. 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;

  2. Qwen Assistant

    To display the serving size on your front end, you need to ensure that the component renders the servingSize value directly from the foodData object, 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 foodData changes after an API call. This leads to stale or incorrect serving size data being potentially displayed.


    ✅ Solution: Use foodData.servingSize Directly

    Instead of keeping a separate state for servingSize, use the value directly from the foodData object, which is updated whenever the backend returns new data.


    ✅ Implementation

    1. Remove the unnecessary state:
    // ❌ Remove this line:
    const [servingSize, setServingSize] = useState(nutrition.servingSize);
    
    1. 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 servingSize is in the API Response

    Make sure that your backend always includes the servingSize field 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 WrongWhat to Fix
    Unused servingSize stateRemove the state and use foodData.servingSize instead
    No UI element for serving sizeAdd a <p> or <label> to display foodData.servingSize
    Potential stale dataAvoid keeping redundant state; rely on foodData for 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.