Mastering Steem Condenser with React Infinite Query: Part 1
Hello Steem Developers,
Today, I'm sharing a detailed tutorial on using React Query with the Steem Condenser Bridge API. The Bridge API allows us to fetch posts infinitely, but how can we optimize this process? Let's dive into a simple and efficient implementation.
First, we need to install these two dependencies in our project:
npm install @tanstack/react-query
npm install https://github.com/faisalamin9696/dhive
If you're using React Query for the first time, you need to set it up correctly in your project. Follow the guidelines here.
For setting up the Steem client with Dhive, follow the instructions here. Use the Steem RPC https://api.steemit.com.
export let client = new Client("https://api.steemit.com", {
timeout:5000,
addressPrefix: "STM",
chainId: "0000000000000000000000000000000000000000000000000000000000000000",
failoverThreshold: 10,
consoleOnFailover: true,
});
our client is now ready and we can use it to access the steem blockchain operations. Let's export a general function to fetch data from the get_ranked_posts bridge API. In this function, the first param is a category and its type is imported from the dhive, the second param is an observer we will use it for a login user. Next params start_author and start_permlink will be used to fetch the next batch of posts when the end reaches of out feed list. It will be the author and permalink of the last post in the fetched post data.
export const getActiveFeed = async (
category: DiscussionQueryCategory,
observer: string = 'null',
start_author?: string,
start_permlink?: string,
limit: number = 10,
): Promise<Post[]> => {
try {
if (!category) {
throw new Error('Invalid request');
}
const response = await client.call2('bridge', 'get_ranked_posts', {
sort: category,
tag: '',
observer: observer,
limit,
start_permlink,
start_author,
});
if (response) {
return response as Post[];
} else {
throw new Error(response);
}
} catch (error: any) {
// log and re-throw any errors that occur
console.error('Failed to fetch data:', error);
throw new Error(error);
}
};
Now we are ready to use this function with react query. In our feed page let's use the useInfiniteQuery.
You can define custom queryKey and call the getActiveFeed in queryFn, define the initial params and in getNextPageParam we will return the author and permalink of the last post in the currently fetched data. We can use these hooks fetchNextPage, isFetchingNextPage, isPending, error, data, refetch provided by useInfiniteQuery
const {fetchNextPage, isFetchingNextPage, isPending, error, data, refetch} =
useInfiniteQuery({
queryKey: ['feed-trendings'],
queryFn: ({pageParam}) =>
getActiveFeed(
'trending',
'faisalamin',
pageParam.start_author,
pageParam.start_permlink,
),
initialPageParam: {
start_author: '',
start_permlink: '',
},
getNextPageParam: (lastPage, allPages) => {
const lastPost = lastPage[lastPage.length - 1];
return {
start_author: lastPost.author,
start_permlink: lastPost.permlink,
};
},
});
Now we can use the data to show all the posts in the list, In my case, I am using React native project so I will go with Flatlist,
To fetch the next page means the next 10 posts we will use the onEndReached function and call the fetchNextPage. To render the list items I am using a custom layout CommentCard you can use any layout to render the items.
<FlatList
removeClippedSubviews
scrollEventThrottle={16}
initialNumToRender={6}
maxToRenderPerBatch={6}
contentContainerStyle={{
gap: 4,
}}
keyExtractor={item => `${item.post_id}`}
data={data.pages.flat()}
renderItem={({item}) => {
return <CommentCard comment={item} />;
}}
onEndReached={() => {
fetchNextPage();
}}
onEndReachedThreshold={1}
ListFooterComponentStyle={{padding: 4}}
ListFooterComponent={() => {
return isFetchingNextPage ? (
<ActivityIndicator size={'small'} />
) : null;
}}
/>
Here is the result
Visit here.
https://www.steempro.comSteemPro Official Discord Server
https://discord.gg/Bsf98vMg6U
Experience the future of blogging with SteemPro Blogs today!
Cc:
@steemchiller
@pennsif
@steemcurator01
@rme
https://www.steempro.com/witnesses
VOTE @faisalamin as witness
Don't know much about this language i mean coding language but i will must say, worth doing .👏👏
Thank you @artist1111 , you must give it a try
Congratulations, your post has been upvoted by @dsc-r2cornell, which is the curating account for @R2cornell's Discord Community.
Congratulations, your post has been upvoted by @dsc-r2cornell, which is the curating account for @R2cornell's Discord Community.