03_lesson: use postStatus to fetch content and display correspondingly
This commit is contained in:
parent
2339529dfd
commit
e8dedad084
19
02_lesson_starter/src/features/posts/PostsExcerpt.js
Normal file
19
02_lesson_starter/src/features/posts/PostsExcerpt.js
Normal 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;
|
@ -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>
|
||||
);
|
||||
};
|
||||
|
Loading…
x
Reference in New Issue
Block a user