React setState not updating but console logging the value

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

Can you please in future format your code at least halfway sensibly. I have just spent ten minutes trying to do this on a mobile phone.

If you don’t bother doing this it is extremely difficult to read, you are combining that with a large amount of complicated code.

Anyway, apologies for the slight rant, it’s just difficult to figure things out when code is extremely hard to read. So where I got to:

Am I actually correct in thinking that you’ve nested literally everything inside this function Apple? Because if so, yeah the code will probably not do what you expect. You have a single component, not multiple ones, and it’s going to recursively update itself and do weird things.

You’re massively overcomplicating things by having nested, interconnected state and props.

React works by basically just having a set of functions that are nested within one another: props are passed as arguments, so props change, which runs a child function, whose props change, which runs a child function and so on.

Can you, right now, explain the update process. Like, if you change the state at one level, which functions does it rerun. And when they rerun, what functions rerun?

This is unlikely, because you’re

  • basing state off props (what happens when the props change? What happens to the state derived from the state based on props when either the props or the state changes?)
  • basing state off props + new state (which one updates first? What happens to the state when the props change? What happens to the props when the state changes?)
  • doing all thisinside one “God” function

So first, take all of those nested functions out. Try to put the state in one place, at the top, and if possible just use props for the children.

1 Like