44*/
55
66
7- import React , { useState } from 'react' ;
7+ import React , { useState , useEffect , useRef } from 'react' ;
88import Navbar from './components/Navbar' ;
99import Hero from './components/Hero' ;
1010import ProductGrid from './components/ProductGrid' ;
@@ -25,16 +25,26 @@ function App() {
2525 const [ view , setView ] = useState < ViewState > ( { type : 'home' } ) ;
2626 const [ cartItems , setCartItems ] = useState < Product [ ] > ( [ ] ) ;
2727 const [ isCartOpen , setIsCartOpen ] = useState ( false ) ;
28+ // Stores the section id to scroll to after a view change
29+ const pendingScrollRef = useRef < string | null > ( null ) ;
30+
31+ // Scroll to the pending section once the home view has mounted
32+ useEffect ( ( ) => {
33+ if ( view . type === 'home' && pendingScrollRef . current !== null ) {
34+ const targetId = pendingScrollRef . current ;
35+ pendingScrollRef . current = null ;
36+ scrollToSection ( targetId ) ;
37+ }
38+ } , [ view ] ) ;
2839
2940 // Handle navigation (clicks on Navbar or Footer links)
3041 const handleNavClick = ( e : React . MouseEvent < HTMLAnchorElement > , targetId : string ) => {
3142 e . preventDefault ( ) ;
3243
33- // If we are not home, go home first
44+ // If we are not home, go home first and defer the scroll to the useEffect above
3445 if ( view . type !== 'home' ) {
46+ pendingScrollRef . current = targetId ;
3547 setView ( { type : 'home' } ) ;
36- // Allow state update to render Home before scrolling
37- setTimeout ( ( ) => scrollToSection ( targetId ) , 0 ) ;
3848 } else {
3949 scrollToSection ( targetId ) ;
4050 }
@@ -72,9 +82,7 @@ function App() {
7282 } ;
7383
7484 const removeFromCart = ( index : number ) => {
75- const newItems = [ ...cartItems ] ;
76- newItems . splice ( index , 1 ) ;
77- setCartItems ( newItems ) ;
85+ setCartItems ( prev => prev . filter ( ( _ , i ) => i !== index ) ) ;
7886 } ;
7987
8088 return (
@@ -109,8 +117,8 @@ function App() {
109117 < ProductDetail
110118 product = { view . product }
111119 onBack = { ( ) => {
120+ pendingScrollRef . current = 'products' ;
112121 setView ( { type : 'home' } ) ;
113- setTimeout ( ( ) => scrollToSection ( 'products' ) , 50 ) ;
114122 } }
115123 onAddToCart = { addToCart }
116124 />
0 commit comments