I have this list of products on a ReactJS store:
{productsList.map((product) => (
<ProductItem
product={product}
/>
)}
When I add more products in this list, the scroll position goes to the end of the list. The code to add more products:
function nextPage() {
getMoreProducts().then((newProducts)=> {
setProductsList(productsList.concat(newProducts))
})
}
I need to keep the scroll position, because this way the user have to scroll to top to see the loaded new products.
I have try storing the scroll position, but the changes are done before the list grow, so nothing happens:
function nextPage() {
const actualScrollPosition = window.pageYOffset
getMoreProducts().then((newProducts)=> {
setProductsList(productsList.concat(newProducts)) //<- setState from React is async.
window.scroll({ top: actualScrollPosition, behavior: "smooth" });
})
}