Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 139805

React display n number of elements on page and keep the rest idle

$
0
0

I am creating a react app and I want to show only show 21 number of elements at a time and keep the rest in idle and show another 21 elements when scroll to bottom of page.

I have my function _injectAdsInList that gets the products and insets an add every 20 products this works but when I want to only show 21 elements at a time (20 products and 1 add) while keeping the rest idle to load another 21 elements when they scroll down I get an error on the screen and in my console doing a console log my array displayedList is coming back as undefined.

this is my component

import React from "react";
import { Loading } from "./LoadingComponent";

const axios = require('axios');

class Products extends React.Component {


  constructor(props){
        super(props);
        this.state = {
      displayedList : [],
      indexDisplayed : 0,
      isLoading: false,
      error: null
    }
    }



  _injectAdsInList = list => {
    // an array of your ads

    this.setState({ isLoading: false });
    const AdsList = ['111','2222'];

    let displayedList = this.state.displayedList;
    let indexDisplayed = this.state.displayedList;

    if (Array.isArray(list)) {
      const insertAdAt = 21;

      const productsAndAdsList = list.map((item, index) => {
        // not sure about this calculation
        // but this should be done here

        if (index % insertAdAt === 0 && index !== 0) {
          // its the 20th item insert an ad
          return AdsList[0];
        }

        // otherwise insert the item


        return item;



        });


        for(let i = indexDisplayed; i <= indexDisplayed + 21; i++ ){
         displayedList.push(productsAndAdsList[i]);
        }





      this.setState({ productsAndAdsList,

            indexDisplayed  : this.state.indexDisplayed+21, 
            displayedList : displayedList     });



    }
  };





  _getProducts = () => {

    this.setState({ isLoading: true });

    axios.get('http://localhost:3000/products').then(list => this._injectAdsInList(list.data))
      .catch(error => this.setState({ error, isLoading: false }));
  };


  _sortPrice = () => {
    const { displayedList } = this.state;

    const sortedProducts = displayedList.sort((a, b) => a.price - b.price);
    this.setState({ displayedList: sortedProducts });
  };

  _sortSize = () => {
    const { displayedList } = this.state;

    const sortedProducts = displayedList.sort((a, b) => a.size - b.size);
    this.setState({ displayedList: sortedProducts });
  };

  _sortId = () => {
    const { displayedList } = this.state;  
    const sortedProducts =  displayedList.sort((a, b) => {
  if (a.id < b.id)
    return -1;
  if (a.id > b.id)
    return 1;
  return 0;
});
    this.setState({ displayedList: sortedProducts });
  }

   _timeAgo = (prevDate) => {
        const diff = Number(new Date()) - prevDate;
        const minute = 60 * 1000;
        const hour = minute * 60;
        const day = hour * 24;
        const month = day * 30;
        const year = day * 365;
        switch (true) {
            case diff < minute:
                const seconds = Math.round(diff / 1000);
                 return `${seconds} ${seconds > 1 ? 'seconds' : 'second'} ago`
            case diff < hour:
                return Math.round(diff / minute) + ' minutes ago';
            case diff < day:
                return Math.round(diff / hour) + ' hours ago';
            case diff < month:
                return Math.round(diff / day) + ' days ago';
            case diff < year:
                return Math.round(diff / month) + ' months ago';
            case diff > year:
                return Math.round(diff / year) + ' years ago';
            default:
                return "";
        }
    };

  componentDidMount() {

    this._getProducts();
  }

  render() {

    const { displayedList, isLoading, hasError } = this.state;

console.log(this.state.displayedList);

    // show spinner
    if (!hasError && isLoading) {
      return <Loading />;
    }

    // show error
    if (hasError && !isLoading) {
      return <p>error.message</p>;
    }

    return (
      <div>
       <div className="row">
            <div className="col-12">
                <button onClick={this._sortPrice}>sort by price lower to higher</button>
                <button onClick={this._sortSize}>sort by size small to big</button>
                <button onClick={this._sortId}>sort by Id</button>  
            </div>  
        </div>
        { displayedList.map(item => { return (
                        <div className="row">
              <div className="col-4">
                <p> Price: ${(item.price / 100).toFixed(2)}</p>
              </div>

              <div className="col-4">
                <p style={{ fontSize: `${item.size}px` }}> {item.face}</p>
              </div>
            <div className="col-3">
                  <p>Published: {this._timeAgo(new Date(item.date).getTime())}</p>
                </div>
            </div>
            ) } )

                }



       <div className="row">
            <div className="col-12">
                <p>END OF CATALOG</p>  
            </div>  
        </div>
      </div>
    );
  }
}

export default Products;

Viewing all articles
Browse latest Browse all 139805

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>