I’m building a blog application in React where each blog displays a list of comments. Each comment includes:
- Like count (total number of likes for the comment)
- Like status (whether the currently logged-in user has liked the comment)
There are two scenarios I’m considering:
When the user is not logged in: Since there’s no logged-in user, the like status for all comments would be false. Should I:
- Fetch only the comments and their like counts in a single API call(like status will be false for all as user is not logged in)?
- Fetch comments first and then make additional calls to fetch like status of each comment using useEffect?
When the user logs in:
After login, the UI needs to reflect the correct like status for each comment based on the logged-in user. Should I:
- Refetch all comments, their like counts, and the like status for the logged-in user in one big API call?
- Fetch only the like status for the logged-in user in a separate API call for each comment using useEffect and update the previously fetched comments?
Considerations:
The number of comments per blog can vary and I want to ensure the solution is efficient, minimizes backend load, and provides a smooth user experience. I’m also using a relational database where comments and likes have a one-to-many relationship.
Which approach would you recommend for each scenario, and why? Are there alternative patterns or best practices I should consider for optimizing these API calls?
Thank you in advance for sharing your insights!
1 Answer 1
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function CommentsList() {
const [comments, setComments] = useState([]);
useEffect(() => {
// Fetch comments with like counts
axios.get('/api/comments')
.then(response => {
// Map comments to include likeStatus as false for all
const commentsWithStatus = response.data.map(comment => ({
...comment,
likeStatus: false
}));
setComments(commentsWithStatus);
})
.catch(error => console.error('Error fetching comments:', error));
}, []);
return (
<div>
{comments.map(comment => (
<Comment key={comment.id} comment={comment} canLike={false} />
))}
</div>
);
}
// Comment component
function Comment({ comment, canLike }) {
return (
<div>
<p>{comment.text}</p>
<span>Likes: {comment.like_count}</span>
{!canLike && <span> (Log in to like)</span>}
</div>
);
}