Why Load More Feature is Important | A simple way to implement it

in hive-150122 •  2 years ago 

Hello Steemians,

I hope you all are well. We are here in the community to stay united. Every developer is trying to achieve future goals for steem. A most demanded dApp for the Steem is STeemPro. I am working on it for the last 3 months. Today We will discuss the road to more functionality in the app.

loadmore.png
Created using Canva

What is Load More Functionality

When we open the app it fetches the data from the steem condenser API. We send the limit variable that accepts value in number (integer). It limits the number of data fetched through our API request. A question rise here, Why do we set the limit?

Why it is important

Suppose that we do not set the limit then it will run the default limit maybe it is 100, which means the API response gives us 100 lists of posts. It required additional time to fetch the 100 posts. But wait, what if the end user does not want to read the entire list of 100 posts? then why we are using the network? It also increases the response time of our app. To tackle this issue we set the limit to 5-10 or as per need. When a user opens the app we send the request with a limit of 10. API response in less time and end-user network usage is reduced significantly. If the user wants to read more posts he/she scrolls down the list there we use the method of list onEndReached. When the end of the list is reached we send a new request to fetch more posts with a defined limit.

How to

What if a developer needs to implement this functionality? There is no pagination like the method is available on YouTube or the web. I will share the useful methods here so that you can easily implement them in your app or if you have a better version than this you can share it in the comment section. I use the typescript but you can use the same method with a little change in the Javascript project too.

First We need a method to send the API request


interface PostRef {
  author: string;
  permlink: string;
}

const fetchPostsData = async (
  category: string,
  tag: string,
  startPostRef: PostRef,
  username: string = '',
  limit: number = NUM_FETCH_POSTS + 1,
  filterNsfw: boolean = true,
): Promise<PostData[]> => {
  // build query
  const query: DisqussionQuery = {
    tag: tag,
    limit: limit,
    start_permlink: startPostRef.permlink || undefined,
    start_author: startPostRef.author || undefined,
    truncate_body: TRUNCATE_BODY_LENGTH, // @todo what if no trucate?
  };

  try {
    const posts = await client.call(
      'condenser_api',
      `get_discussions_by_${category}`,
      [query],
    );
   // fetched data on posts const

    return posts;
  } catch (error) {
    console.error('failed to get posts summaries', error.message);
    return [];
  }
};

You can map the data with your modal class or can also use this raw fetched data.

No, we will call this fetchPostsData function on the page where we need to show the list of posts. Here is the initial fetch. When the user opens the app it will trigger in didComponentMounted or useEffect.


  const [fetchedData, setFetchedData] = useState([]);
  const [fetchAll, setFetchAll] = useState(false);
  const [initialFetch, setInitialFetch] = useState(false);
  const [isReloding, setIsReloding] = useState(false);
  const [limit, setLimit] = useState(10)

 useEffect(() => {
    setIsReloding(true);
    if (!initialFetch) {
      console.log('useEffect');
      _fetchPosts();
    }
  });


let tag = '';
  const { username } = '';
  let startPostRef = {
    author: null,
    permlink: null,
  };
const filter = 'trending';

  const _fetchPosts = async () => {
    if (!initialFetch) {
      await fetchPostsData (filter, tag, startPostRef, username, limit, true).then((res) => {
        console.log('[FetchedSummary]', res);
        setFetchedData(res);
        setFetchAll(true);
        setIsReloding(false);
        setInitialFetch(true);
      }).catch((e) => {
        // console.error(e);
      })
    }
  };

In the FlatList we will see the onEndReached property.

 <FlatList
                data={fetchedData}
                renderItem={({ item, index }) => _renderItem(item, index)}
                keyExtractor={(item, index) => index.toString()}
                onEndReached={() => { _loadMore(lastAuthor, lastPermLink) }}
                ListFooterComponent={_renderFooter()}
                onEndReachedThreshold={1}
            />

In _renItem we need to save the last post reference like this:

const _renderItem = (item, index) => {
        if (index == props.postsData.length - 1) {
            lastPermLink = item.state.post_ref.permlink;
            lastAuthor = item.state.post_ref.author;
        }

        return (
           <></>
           { /* You Views */}
        )

    };

Now here is the interesting part of the _loadMore function. We will send a request with the post reference of the last post. Api will get only the posts after the last fetched post reference. We will concat the old data and newly fetched data. We will remove the item at the 0 positions as it is a duplicate. We slice the list and start it from 1 to end.

  const _loadMore = async (lastAuthor, lastPermLink) => {
    console.log(lastAuthor, lastPermLink);
    await fetchPostsData (filter, tag, { author: lastAuthor, permlink: lastPermLink }, username, limit + 1, true).then((res) => {
      console.log('[moreData]', res);
      setFetchedData(fetchedData.concat(res.slice(1)));
      setIsReloding(false);
    }).catch((e) => {
      console.error(e);
    })
  }

That's all you are successfully implementing the load more functionality. If you need any help regarding this let me know in the comment section.

Happy Coding !!!

Special Thank to:


@rme
@blacks
@hungry-griffin


VOTE @bangla.witness as witness


witness_vote.png

OR

SET @rme as your proxy

witness_proxy_vote.png

▀▄▀▄▀▄ T̳̿͟͞h̳̿͟͞a̳̿͟͞n̳̿͟͞k̳̿͟͞s̳̿͟͞ ̳̿͟͞f̳̿͟͞o̳̿͟͞r̳̿͟͞ ̳̿͟͞R̳̿͟͞e̳̿͟͞a̳̿͟͞d̳̿͟͞i̳̿͟͞n̳̿͟͞g̳̿͟͞ ▄▀▄▀▄▀

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thanks @ faisalamin, for the informative article

My Pleasure...

Congratulations, your post has been upvoted by @dsc-r2cornell, which is the curating account for @R2cornell's Discord Community.

Manually curated by @jasonmunapasee

r2cornell_curation_banner.png

Assalamualaikum Faisal brother, I made a request to you that I have posted in hive but it was not verified. I also bought 27 hive and I also powered it up after that my post was not verified. I also shared the link of my post but you didn't reply bro what will happen if you guide me as a Pakistani you are my most senior so if you tell me it will be very kind.

Discord servers are available for the communities. You can ask your questions there.

bro i don't have their discord plz share me the link pls be kind because i have been in it for a long time but i didn't get anything pls give me the discord i'd thank you.

Check the pinned posts in the community.