javascriptreactjsarraysloopsslice

javascript setting a .map() range and update the range later


I'm building an app with React & JS which returns products from a json list inside a component, the array is outputted on the app using a .map() array. I'm also limiting the amount to return initially in the map using a .slice(0, 30) to return the first 30 products.

However I also want to be able to update the range on the click of a button later to then load 60 products (include the next 30 products with the original 30):

products.slice(0, 60).map(product => (......));

(products. is just the variable that is storing the json array in my code)

I don't know if there's a way to update or reload a map with the new slice amount, or if there's a better way than using .slice() to do this?

I tried adding a click event to a button which runs a function that updates a variable containing the max number of products to return let numberOfProductsToShow = 30 that takes the original number and adds 30 numberOfProductsToShow = numberOfProductsToShow + 30; and then running the same function again with the updated max value passed to the slice .slice(0, numberOfProductsToShow).

    const productList = document.querySelector('.productsList .products');
    productList.innerHTML = propductsMap(0, numberOfProductsToShow);

but this just returns the words [object Object],[object Object],[object Ob...etc 60 times so that's obviously not correct.

More code as requested for initial reopening:

import React, { useState, useEffect } from 'react'
import productData from './assets/products.json'

const App = () => {

  const [products, setProducts] = useState([])
  
  
  useEffect(() => {
    setProducts(productData.products);
  })
  
  let numberOfProductsToShow = 30;
  
  const propductsMap = (loadFrom, loadTo) => {
    return (
      products.slice(loadFrom, loadTo).map(product => (

        <div className='product' key={product.id}>
          <div className='productImage'>
            <img src="" data-src={product.thumbnail} />
          </div>
          <div className='productInfo'>
            <div className='productTitle'>
              <div className='productBrand'>{product.brand}</div> 
              <div className='productName'>{product.title}</div>
            </div>
            <div className='productPrice'>Price: {product.price}</div>
          </div>
          
        </div>
      ))
    )
  }
  
  const viewMoreButton = document.querySelector('.viewMore button');
    const productList = document.querySelector('.productsList .products');
    viewMoreButton.addEventListener('click', () => {
      loadMoreProducts();
    });

    const loadMoreProducts = () => {
      numberOfProductsToShow = numberOfProductsToShow + 30;
      productList.innerHTML = propductsMap(0, numberOfProductsToShow);
    };
    
    return (
    <div className='shopperApp'>
      <Header />

      <div className='productsList'>
        <div className='products'>
          {propductsMap(0, numberOfProductsToShow)}
        </div>        
        <div className='viewMore'><button>View More</button></div>
      </div>

      

    </div>
  )
}

export default App
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>


Solution

  • The JSON file needed a Limit object and value adding along side the products list:

    {
      "products": [
        {
        ...
        }
      ],
      "limit": 30
    

    Create a second useState which stores and allows the limit value to be updated, then add that initial useState variable to the .slice() to return the initial number of products set by the JSON limit value:

    const [productsLimit, setProductsLimit] = useState(productData.limit)
    
    productData.products.slice(0, productsLimit).map(product => (
            <div className='product' key={product.id}>
              <div className='productImage'>
                <img src="" data-src={product.thumbnail} />
              </div>
              <div className='productInfo'>
                <div className='productTitle'>
                  <div className='productBrand'>{product.brand}</div> 
                  <div className='productName'>{product.title}</div>
                </div>
                <div className='productPrice'>Price: {product.price}</div>
              </div>
              
            </div>
          ))
    

    Finally the button just needs to be made to update the new useState with a new value to increase the amount of products to show:

    const viewMoreButton = document.querySelector('.viewMore button');
    viewMoreButton.addEventListener('click', () => {
      setProductsLimit(productsLimit + productData.limit);
    });
    

    Answer provided by question author.