By BARNOWL


2020-05-22 23:15:37 8 Comments

I have a react component that upon clicking showMore. it will load more comments. The issue im facing is that

View {showMore} More Comments

is not showing the items that are left in the array. Currently there are 7 comments in an array, and if you click show more, it will initially read show 3 more, but when i click again it says show 6 more. when it should be a lesser number than 6. It should be like show 2 more, etc. I'm quite confused on how to go about writing this logic.

What am i doing wrong

CommentList.tsx

import React, { Fragment, useState } from "react";
import Grid from "@material-ui/core/Grid";
import List from "@material-ui/core/List";
import Typography from "@material-ui/core/Typography";
import CommentItem from "./../commentItem/CommentItem";
import moment from "moment";
import OurLink from "../../../common/OurLink";
import OurSecondaryButton from "../../../common/OurSecondaryButton";
import OurModal from "../../../common/OurModal";
.....
function CommentList(props: any) {
    const [showMore, setShowMore] = useState<Number>(3);
    const [openModal, setOpenModal] = useState(false);
    const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
    const the_comments = props.comments.length;
    const inc = showMore as any;
    const showComments = (e) => {
        e.preventDefault();
        if (inc + 3 <= the_comments) {
            setShowMore(inc + 3);
        } else {
            setShowMore(the_comments);
        }
        // setShowLessFlag(true);
    };
    ........
    const showMoreComments = () => {
        return props.comments
            .slice(0, showMore)
            .sort((a, b) => a.id - b.id)
            .map((comment, i) => (
                <div key={i}>
                    <List style={{ paddingBottom: "20px" }}>
                        <img alt="gravatar" style={{ margin: "-10px 15px" }} src={comment.author.gravatar} width="30" height="30" />
                        <Typography style={{ display: "inline-block", fontWeight: 700, padding: "5px 0px" }} variant="h6" align="left">
                            {Object.entries(props.currentUser).length === 0 ? (
                                <Fragment>
                                    <span style={{ cursor: "pointer", fontSize: "12px", fontWeight: isBold(comment) }} onClick={handleClickOpen}>
                                        {comment.author.username}
                                    </span>
                                    {comment.userId === props.userId && <span style={{ fontSize: "12px" }}> (OP)</span>}
                                    {openModal ? <OurModal open={openModal} handleClose={handleCloseModal} /> : null}
                                </Fragment>
                            ) : (
                                <Fragment>
                                    <OurLink
                                        style={{ fontSize: "12px", fontWeight: isBold(comment) }}
                                        to={{
                                            pathname: `/profile/${comment.author.username}`,
                                        }}
                                        title={comment.author.username}
                                    />
                                    {comment.userId === props.userId && <span style={{ fontSize: "12px" }}> (OP)</span>}
                                </Fragment>
                            )}
                        </Typography>
                        <div style={ourStyle}>
                            <CommentItem comment={comment} user={props.user} postId={props.postId} {...props} />
                            <Typography style={{ fontSize: "12px" }} variant="body1" align="left">
                                {moment(comment.createdAt).calendar()}
                            </Typography>
                        </div>
                    </List>
                </div>
            ));
    };

    console.log(props.comments.slice(0, showMore).length);

    return (
        <Grid>
            <Fragment>
                <div style={{ margin: "30px 0px" }}>
                    <OurSecondaryButton onClick={(e) => showComments(e)} component="span" color="secondary">
                        View {showMore} More Comments
                    </OurSecondaryButton>
                </div>
            </Fragment>
            {showLessFlag === true ? (
                // will show most recent comments below
                showMoreComments()
            ) : (
                <Fragment>
                    {/* filter based on first comment  */}
                    {props.comments
                        .filter((item, i) => item)
                        .sort((a, b) => b.id - a.id)
                        .slice(0, showMore)
                        .map((comment, i) => (
                            <div key={i}>
                                <List style={{ paddingBottom: "20px" }}>
                                    <img alt="gravatar" style={{ margin: "-10px 15px" }} src={comment.author.gravatar} width="30" height="30" />
                                    <Typography style={{ display: "inline-block", fontWeight: 700, padding: "5px 0px" }} variant="h6" align="left">
                                        {Object.entries(props.currentUser).length === 0 ? (
                                            <Fragment>
                                                <span style={{ fontSize: "12px", cursor: "pointer", fontWeight: isBold(comment) }} onClick={handleClickOpen}>
                                                    {comment.author.username}
                                                    {comment.userId === props.userId && <span style={{ fontSize: "12px" }}> (OP)</span>}
                                                </span>

                                                {openModal ? <OurModal open={openModal} handleClose={handleCloseModal} /> : null}
                                            </Fragment>
                                        ) : (
                                            <Fragment>
                                                <OurLink
                                                    style={{ fontSize: "12px", fontWeight: isBold(comment) }}
                                                    to={{
                                                        pathname: `/profile/${comment.author.username}`,
                                                    }}
                                                    title={comment.author.username}
                                                />
                                                {comment.userId === props.userId && <span style={{ fontSize: "12px" }}> (OP)</span>}
                                            </Fragment>
                                        )}
                                    </Typography>

                                    <div style={ourStyle}>
                                        <CommentItem comment={comment} user={props.user} postId={props.postId} {...props} />
                                        <Typography style={{ fontSize: "12px" }} variant="body1" align="left">
                                            {moment(comment.createdAt).calendar()}
                                        </Typography>
                                    </div>
                                </List>
                            </div>
                        ))}
                </Fragment>
            )}
        </Grid>
    );
}
// prevents un-necesary re renders
export default React.memo(CommentList);

1 comments

@user120242 2020-05-22 23:39:46

You want to show 3 more comments each time, or 1-2 items if there are less than 3 items left. So "View 3 More comments" if there are more than 3 left, or "View 1/2 More Comments" if there are only 1 or 2 left.
Or in other words cap the number of new comments shown at 3:
the minimum value of either 3 or (total number of comments - current shown comments = number of comments left).

View {Math.min(3, the_comments - inc)} More Comments

@BARNOWL 2020-05-22 23:41:35

ok now im starting to understand, i really appreciate this :)

Related Questions

Sponsored Content

20 Answered Questions

[SOLVED] Javascript - sort array based on another array

  • 2012-11-09 08:29:02
  • user1448892
  • 113923 View
  • 164 Score
  • 20 Answer
  • Tags:   javascript

13 Answered Questions

[SOLVED] JavaScript Array splice vs slice

  • 2016-06-02 20:13:40
  • Renat Gatin
  • 252971 View
  • 191 Score
  • 13 Answer
  • Tags:   javascript

15 Answered Questions

[SOLVED] How to filter object array based on attributes?

  • 2010-04-27 14:42:39
  • JGreig
  • 760135 View
  • 482 Score
  • 15 Answer
  • Tags:   javascript

1 Answered Questions

Javascript array slicing based on filter

21 Answered Questions

[SOLVED] Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

8 Answered Questions

[SOLVED] How to sort an array based on the length of each element?

12 Answered Questions

[SOLVED] Remove array element based on object property

19 Answered Questions

[SOLVED] What is the most efficient way to concatenate N arrays?

  • 2011-02-22 15:20:36
  • Leonid
  • 194738 View
  • 252 Score
  • 19 Answer
  • Tags:   javascript arrays

7 Answered Questions

[SOLVED] What does it mean that Javascript is a prototype based language?

Sponsored Content