How to create a 'Load More' feature without re-rendering entire component in React/Node?

Viewed 1194

I'm trying to create a simple poll app, where you can make new polls.

In the section 'MyPolls', I want it to render only the first 5 polls that I've made instead of rendering the entire list of polls.

At the bottom is a 'Load More' button, where upon clicking, loads another 5 polls and so on.

I've been using Mongoose/MongoDB backend and my approach has been to use skip and limit.

I've managed to implement this feature, but the problem is the entire component re-renders, which is annoying for a user as you have to scroll down again the click the 'Load More' button.

Here is my app: https://voting-app-drhectapus.herokuapp.com/

(use can you these login details for convenience: username: riverfish@gmail.com password: 123)

And then goto the My Polls page.

MyPoll.js:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';

class MyPolls extends Component {
  constructor(props) {
    super(props);
    this.state = {
      skip: 0
    };
  }

  componentDidMount() {
    this.props.fetchMyPolls(this.state.skip);
    this.setState({ skip: this.state.skip + 5 });
  }

  sumVotes(polls) {
    return polls.reduce((a, b) => {
      return a.votes + b.votes;
    });
  }

  loadMore(skip) {
    this.props.fetchMyPolls(skip);
    const nextSkip = this.state.skip + 5;
    this.setState({ skip: nextSkip });
  }

  renderPolls() {
    return this.props.polls.map(poll => {
      return (
        <div className='card' key={poll._id}>
          <div className='card-content'>
            <span className='card-title'>{poll.title}</span>
            <p>Votes: {this.sumVotes(poll.options)}</p>
          </div>
        </div>
      )
    })
  }

  render() {
    console.log('polls', this.props.polls);
    console.log('skip:', this.state.skip);
    return (
      <div>
        <h2>My Polls</h2>
        {this.renderPolls()}
        <a href='#' onClick={() => this.loadMore(this.state.skip)}>Load More</a>
      </div>

    );
  }
}

function mapStateToProps({ polls }) {
  return { polls }
}

export default connect(mapStateToProps, actions)(MyPolls);

Action creator:

export const fetchMyPolls = (skip) => async dispatch => {
  const res = await axios.get(`/api/mypolls/${skip}`);

  dispatch({ type: FETCH_MY_POLLS, payload: res.data });
}

Poll route:

app.get('/api/mypolls/:skip', requireLogin, (req, res) => {

    console.log(req.params.skip);

    Poll.find({ _user: req.user.id })
      .sort({ dateCreated: -1 })
      .skip(parseInt(req.params.skip))
      .limit(5)
      .then(polls => {
        res.send(polls);
      });
  });

Entire github repo: https://github.com/drhectapus/voting-app

I understand that might method of implementing this feature might be the best possible solution so I'm open to any suggestions.

1 Answers

It looks like the re-render is triggered by the fact that clicking the "Load More" link actually causes react router to navigate to a new route, causing the entire MyPolls component to re-render.

Just replace the <a href='#' onClick={...}> with <button onClick={...}>.

If you don't want to use a button, you could also change the onClick function to

const onLoadMoreClick = e => {
    e.preventDefault(); // this prevents the navigation normally occuring with an <a> element
    this.loadMore(this.state.skip);
}
Related