Hi I’m trying to update the state in React but unable to do it.
Here is the example how I’ve updated the state setState(()=>item*price);
When I’m console logging the item*price value I’m getting the correct value but the state was unable to update.
Please help me to find where I was wrong.
Below is my code and Description
First I’ve created the Input component and passed the data via props to the MealItem component and then using the meal item I’ve passed the data to the MealItems component using the function.
import {useState} from "react";
function Apple () {
const mealItems = [
{name: "Banana", price: 44, amount: 1},
{name: "Apple", price: 88, amount: 1},
{name: "pineapple", price: 95, amount:1}
];
function Input (props) {
let [targetValue, setTargetValue] = useState(1);
function inputHandler(e) {
setTargetValue (prevValue => e.target.value);
}
function submitHandler(e) {
e.preventDefault();
props.onAddtoCart(props.item, targetValue);
// Passed the data to the MealItem component
}
return (
<form onSubmit ={submitHandler}>
<input value = {targetValue} type="number" step = "1" onChange = {inputHandler} />
<button type = "submit" >Add to cart</button>
</form>
);
}
function MealItems() {
let [cartItemsList, setCartItemsList] = useState([]);
function cartUpdate(item, mealAmount) {
setCartItemsList((cartItemsList)=>[...cartItemsList, item]);
console.log(`${mealAmount} from cartUpdate`);
}
return (
<div>
{ mealItems.map(item => (
<>
<MealItem meal = {item} key = {Math.random()} cartListUpdater = {cartUpdate}/>
</>
));}
</div>
);
}
function MealItem(props){
const meal = props.meal;
const [mealAmount, setMealAmount] = useState(meal.price);
function cartAdder(item, targetValue) {
setMealAmount(()=>item.price*targetValue)
//UNABLE TO UPDATE THE MEALAMOUNT VALUE WHEN I'M console logging I'm getting the item*targetvalue but when I was setting the state of mealAmount I'm getting the inital mealAmount value i.e, meal.price
props.cartListUpdater(meal, mealAmount);
//passed data to MealAmount component
console.log(`this is the ${mealAmount}`);
}
return (
<div>
<ul>
<li>{meal.name}</li>
<li>{meal.price}</li>
<li>{meal.amount}</li>
<li>{mealAmount}</li>
</ul>
<Input item = {meal} key = {Math.random()} onAddtoCart ={cartAdder}/>
<div>{mealAmount} this is the mealAmount</div>
</div>
);
}
return (
<MealItems/>
);
}
export default Apple;
Thanks in Advance