03_lesson: use postStatus to fetch content and display correspondingly

This commit is contained in:
Jason Zhu 2023-03-07 18:10:40 +11:00
parent 2339529dfd
commit e8dedad084
3 changed files with 39 additions and 23 deletions

View File

@ -0,0 +1,19 @@
import ReactionButtons from './ReactionButtons';
import PostAuthor from './PostAuthor';
import TimeAgo from './TimeAgo';
const PostsExcerpt = ({ post }) => {
return (
<article>
<h3>{post.title}</h3>
<p>{post.body.substring(0, 100)}</p>
<p className="postCredit">
<PostAuthor userId={post.userId} />
<TimeAgo timestamp={post.date} />
</p>
<ReactionButtons post={post} />
</article>
);
};
export default PostsExcerpt;

View File

@ -5,43 +5,40 @@ import {
getPostsStatus,
selectAllPosts,
} from './postsSlice';
import PostAuthor from './PostAuthor';
import TimeAgo from './TimeAgo';
import ReactionButtons from './ReactionButton';
import PostsExcerpt from './PostsExcerpt';
import { useEffect } from 'react';
const PostsList = () => {
const dispatch = useDispatch();
const posts = useSelector(selectAllPosts);
const postsStatus = useSelector(getPostsStatus);
const postsError = useSelector(getPostsError);
const postStatus = useSelector(getPostsStatus);
const error = useSelector(getPostsError);
useEffect(() => {
if (postsStatus === 'idle') {
if (postStatus === 'idle') {
dispatch(fetchPosts());
}
}, [postsStatus, dispatch]);
}, [postStatus, dispatch]);
const orderedPosts = posts
.slice()
.sort((a, b) => b.date.localeCompare(a.date));
const renderedPosts = orderedPosts.map((post) => (
<article key={post.id}>
<h3>{post.title}</h3>
<p>{post.content.substring(0, 100)}</p>
<p className="postCredit">
<PostAuthor userId={post.userId} />
<TimeAgo timestamp={post.date} />
</p>
<ReactionButtons post={post} />
</article>
));
let content;
if (postStatus === 'loading') {
content = <p>"Loading...</p>;
} else if (postStatus === 'succeeded') {
const orderedPosts = posts
.slice()
.sort((a, b) => b.date.localeCompare(a.date));
content = orderedPosts.map((post) => (
<PostsExcerpt key={post.id} post={post} />
));
} else if (postStatus === 'failed') {
content = <p>{error}</p>;
}
return (
<section>
<h2>Posts</h2>
{renderedPosts}
{content}
</section>
);
};