0

import React, { useEffect, useState } from 'react'; import { faShoppingBasket, faPlusSquare, faLeaf, faMinusSquare, faTrash } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import './Banner.css';

const Banner = () => { const products = ['Strawberry','Blueberry','Orange','Banana','Apple','Carrot','Celery','Mushroom','Green Pepper','Eggs','Cheese', 'Butter','Chicken','Bread','Pork','Rice','Pasta']; const [cart,setCart] = useState([]);

const addToCart=(prd)=>{

  console.log(prd);
 const exist =  cart.find(product=> product.Name===prd && ++product.Num)
 if(!exist){
  const cartItem={
     Name:prd,
     Num:1
  }
  const newCart = [...cart,cartItem]
  setCart(newCart);
  console.log({cart});
 }

} return ( <div className='mainBanner' style={{height:'250px',background:'#2a2929',color:'white'}}> <div className='logo' style={{paddingTop:'40px',textAlign:'center'}}>

Hello, Basket!

Groceries

{products.map(prd=>

<span onClick={()=>addToCart(prd)}> {prd}

)}
     <div className='cart'>
     <div style={{display:'inline'}}><h3 style={{display:'inline'}}><FontAwesomeIcon icon={faShoppingBasket} size = '2x'/>Basket</h3> 
     <FontAwesomeIcon icon={faTrash} size = '2x'/>
     </div>
      
     {cart.map(prd=> <div className='item'><h3><FontAwesomeIcon icon={faMinusSquare} color='grey'/> {prd.Num}{prd.Name} </h3></div>)}
     </div>
     </div>
  </div>

); };

export default Banner;

  • State changes are asynchronous. You can't `console.log` them on the very next line and see their new value. Put the `console.log` in the main body of the function to see it's real time value – Jayce444 Jul 05 '21 at 07:38
  • dont expect direct update after setXXXX function. these are async functions – Apostolos Jul 05 '21 at 07:39
  • Latest state will appear in rerender phase. Try loging just above where you return jsx. If you are interested to have a deep dive of why state change is asynchronous check this answer by dan abramov https://github.com/facebook/react/issues/11527#issuecomment-360199710 – nikhil mehta Jul 05 '21 at 07:40
  • improve the format and add details explaining your challenge – John Nyingi Jul 05 '21 at 09:00

1 Answers1

0

State changes are asynchronous thus if you will put console.log in the very next line, it won't show updated results. Put console.log outside this addToCart function, You will see the result when the state gets updated.