I am trying to render a row of checkboxes in a table for every ingredient present in an array of ingredients. The problem I am facing is that when I check a checkbox for a particular ingredient, all the checkboxes of for all the ingredients get checked. Can anyone help me? I am attaching the JSON for the meal as well as my solution in the code snippet. any help would be highly appreciated.
const ItemDetails = (props) => {
const [MealDetails, setMEalDetails] = useState([{id:'',name:'',ingredients:[]}]);
const [checkedOne, setCheckedOne] = useState(false);
const [checkedTwo, setCheckedTwo] = useState(false);
const [checkedThree, setCheckedThree] = useState(false);
useEffect(()=>{
const fetchMealDetails = async () =>{
const getMeal = await fetch(""+`${props.mealId}`);
const Meal = [];
const getMealresponse = await getMeal.json();
Meal.push(getMealresponse)
setMEalDetails(Meal);
console.log(getMealresponse)
console.log(Meal);
}
fetchMealDetails()},[])
const handleChangeOne = (event,) => {
setCheckedOne((prevVal,index) => !prevVal);
setCheckedTwo(false);
setCheckedThree(false);}
return(
<div className={classes.itemDetailContainer} >
<div className={classes.topRow}>
<h1>{MealDetails[0].name}</h1>
<h3><i>Quality Score: </i>100%</h3>
<h3><i>Price: </i>$200</h3>
</div>
<div className={classes.IngredientsTable}>
<table className={classes.table}>
<tr className={classes.tr}>
<th className={classes.th}>Ingredients:</th>
<th className={classes.th}>low</th>
<th className={classes.th}>Medium</th>
<th className={classes.th}>High</th>
</tr>
{
MealDetails[0].ingredients.map(
(ingredient,index) =>{
return(
<tr key={index}>
<td className={classes.th} >{ingredient.name}</td>
{ingredient.options.map(
(entry,index) =>
{return <td>
<input type="checkbox" value={entry.quality} key={index} id={index} checked={checkedOne} onChange={handleChangeOne} />
</td>}
)}
</tr>
)
}
)
}
</table>
</div>
<div className={classes.ButtonContainer}>
<Button value="Close" onClick={props.onClick} />
<Button value="Add to Cart" onClick={props.onClick} />
</div>
</div>
)
}
export default ItemDetails;
Array(1)
0
:
id
:
1
ingredients
:
Array(2)
0
:
groups
:
(2) ['vegan', 'vegetarian']
name
:
"Rice"
options
:
Array(3)
0
:
name
:
"Long grain white rice"
per_amount
:
"kilogram"
price
:
3
quality
:
"high"
[[Prototype]]
:
Object
1
:
{name: 'Medium grain brown rice', quality: 'medium', price: 2, per_amount: 'kilogram'}
2
:
{name: 'Quick cooking white rice', quality: 'low', price: 1.5, per_amount: 'kilogram'}
length
:
3
[[Prototype]]
:
Array(0)
quantity
:
120
quantity_type
:
"gram"
[[Prototype]]
:
Object
1
:
{name: 'Chicken', options: Array(3), quantity: 85, quantity_type: 'gram'}
length
:
2
[[Prototype]]
:
Array(0)
name
:
"Rice and chicken bowl"
[[Prototype]]
:
Object
length
:
1
Aucun commentaire:
Enregistrer un commentaire