REACT how to re-fetch to update state to re-render component

36 Views Asked by At

i have this itemCard.jsx component:

  ItemCart({item}) {
   ... 
  const { user } = useContext(AuthContext);
  const [isAdded, setIsAdded] = useState(false);

isAdded state to check if the user already added the item to his shopping cart and it assumes not false as user logging in for the first time


  return (
  ...
      <button
        type="button"
        className="addToCart"
        onClick={() => handleCart(item._id)}
      >
        {isAdded ? "REMOVE FROM CART" : "ADD TO CART"}
      </button>
  ...
)
   ...
}

the button value should say add to cart, and when the user clicks it, it will trigger handleCart function :


  const handleCart = async (itemId) => {

    const response = await fetch(
      `http://localhost:8000/add-or-remove-item-from-cart/${itemId}`,{ method: "POST",headers: {"Content- 
     type": "application/json",}, body: JSON.stringify({userId: user._id}),});
    const data = await response.json();

    setIsAdded(!isAdded);
  };

which makes request to /add-or-remove-item-from-cart/${itemId} and checks if user added this item to his cart it will remove it, otherwise it will add it, for the first time when user clicks add to cart the button value becomes remove from cart as isAdded state changes to true and this works fine

but useEffect must needed to persist state when a new item is added to shopping cart:


  useEffect(() => {
    setIsAdded(user.cartItems.includes(item?._id));
  }, [item?._id, user, user.cartItems]);

but when i refresh the page, the state refreshes and the button value backs to add to cart, when i console logged user, i found out the problem is user state for AuthContext will be the value before the user added any items to user.cartItems, and it won't change until until i update the data on AuthContext therefore localStorage, how to do that?

0

There are 0 best solutions below