React: useState is showing me the previous state value whereas it changes when I look in the DevTools

Usama Nadeem

Necessary imports eg useState, useDispatch

function ItemCard(props) {
  const [count, setCount] = useState(0);
  const dispatch = useDispatch();

Here I am trying to use a button which triggers this function and increases count, but when I console.log it, it prints the older value. When I send the count to dispatch, the older value also gets passed in.

  const addCount = () => {
    setCount((prevCount) => prevCount + 1);
    console.log(count);
    dispatch(
      updateCart(
        "ADD_TO_CART",
        { id: props.id, name: props.name, price: props.price },
        count
      )
    );
  };

  const decreaseCount = () => {
    if (count > 0) {
      setCount((prevCount) => prevCount - 1);
      dispatch(
        updateCart(
          "REMOVE_FROM_CART",
          { id: props.id, name: props.name, price: props.price },
          count
        )
      );
    }
  };

  return (
    <div className="card">
      <div className="image">
        <img src={props.img} alt="cookie" />
      </div>

      <div className="title">
        <h2>{props.name}</h2>
        <h2>Rs.{props.price}</h2>
      </div>

      <p className="detail">{props.detail}</p>

      <div className="buttons">
        <button onClick={addCount} id="add-to-cart">
          +
        </button>
        <span>{count}</span>
        <button onClick={decreaseCount} id="add-to-cart">
          -
        </button>
      </div>
    </div>
  );
}

export default ItemCard;


ludwiguer

setState is async, so you would have to use a local variable or use useEffect to watch when the state is already updated

  const decreaseCount = () => {
    if (count > 0) {
      setCount((prevCount) => prevCount - 1);
    }
  };

  useEffect(() => {
    dispatch(
        updateCart(
          "REMOVE_FROM_CART",
          { id: props.id, name: props.name, price: props.price },
          count
        )
      );
  }, [count])

or

  const decreaseCount = () => {
    if (count > 0) {
      const localCount = count - 1;
      dispatch(
        updateCart(
          "REMOVE_FROM_CART",
          { id: props.id, name: props.name, price: props.price },
          localCount
        )
      );
      setCount((prevCount) => prevCount - 1);
    }
  };

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

UseState loads previous state when value changes (NextJS)

React useState hook - when to use previous state when updating state?

UseState renders me the previous state

How to update useState() when value changes in React

React update useState() when variable value changes

React showing previous state

React useState giving previous state

useState displays previous state when getting value from onChange event

useState updates but when i call the state afterwards it is the previous version?

Is there any way to see names of 'fields' in React multiple state with React DevTools when using 'useState' hooks

setInterval in React component gets duplicated when useState value changes

React state change not showing changes when going back

React UseState - using previous state vs not using previous state

React useState. Why do the docs advise passing a function with the previous state when setting the state?

useState in React Native get data of previous state

React useState didn't catch previous state

How to type the initial state for react context when using useState as value

React input onChange not rerendering state when useState has default value

useState value changes when i call it from child

useState returning an object when adding to previous state

React useState changes my constant initial state

How can i Dynamically Update the React Helmet Value when state changes

react prop value updates when state value changes

How does prevState in new useState in React work ?? How does it store the value of previous state?

React.js component not re-rendering children when the useState hook changes state

React state created with useState doesn't update automatically when my API changes

React useState update based on a variables previous value

React showing previous state ,only updates on refreshing

Button's content look changes when button state changes