About Infinite Scroll in React.js and Material_ui

Viewed 10841

I am on the project with react.js

For the project, I am supposed to include board with infinite scroll like Facebook

In that, I have a question.

When I scroll the board and recall more post like Facebook, is it working

whether it draws only additional posts under the bottom of post or

it recalls the whole list and redraws it

ex) case 1 :  {1,2,3} > scroll > {1,2,3} + {4,5} (additional posts)
    case 2 :  {1,2,3} > scroll > {1,2,3,4,5} (whole posts)

if I do case 1, I wanna know-how.

Thanks!

1 Answers

You should absolutely prefer 1st method. It will enable you to have smaller payload size when you fetch data from api and provide smoother user experience in general.

Let's assume that your api already provides you a way to fetch posts with in certain index-range, example https://myapi.com/posts?start=0&end=10 would return you a list of 10 first posts.

In your React.js -app you should then keep track of latest index you have fetched and when you reach end of page you add to index and fetch for more posts. I pasted here minimalistic codebase for blocks to achieve this, working demo on CodeSandbox

// Store current index of posts
const [startIndex, setStartIndex] = React.useState(0);

const LoadMorePosts = () => {
  // Load 10 more
  setStartIndex(prev => prev + 10);
};

React.useEffect(() => {
  (async () => {
    // Add search range to url
    const url = `?start=${startIndex}&end=${startIndex + 10}`;
    const posts = await mockApi(url);
    // Append new posts to end of old ones
    setPosts(prev => [...prev, ...posts]);
  })();
}, [startIndex]); // Run this effect when startIndex changes
Related