diff --git a/02_lesson_starter/src/features/posts/PostsList.js b/02_lesson_starter/src/features/posts/PostsList.js index bf04115..51c2756 100644 --- a/02_lesson_starter/src/features/posts/PostsList.js +++ b/02_lesson_starter/src/features/posts/PostsList.js @@ -1,11 +1,26 @@ -import { useSelector } from 'react-redux'; -import { selectAllPosts } from './postsSlice'; +import { useDispatch, useSelector } from 'react-redux'; +import { + fetchPosts, + getPostsError, + getPostsStatus, + selectAllPosts, +} from './postsSlice'; import PostAuthor from './PostAuthor'; import TimeAgo from './TimeAgo'; import ReactionButtons from './ReactionButton'; const PostsList = () => { + const dispatch = useDispatch(); + const posts = useSelector(selectAllPosts); + const postsStatus = useSelector(getPostsStatus); + const postsError = useSelector(getPostsError); + + useEffect(() => { + if (postsStatus === 'idle') { + dispatch(fetchPosts()); + } + }, [postsStatus, dispatch]); const orderedPosts = posts .slice() diff --git a/02_lesson_starter/src/features/posts/postsSlice.js b/02_lesson_starter/src/features/posts/postsSlice.js index 1af859c..7560cf0 100644 --- a/02_lesson_starter/src/features/posts/postsSlice.js +++ b/02_lesson_starter/src/features/posts/postsSlice.js @@ -87,6 +87,8 @@ const postsSlice = createSlice({ }); export const selectAllPosts = (state) => state.posts.posts; // first posts is meaning name of the slice +export const getPostsStatus = (state) => state.posts.status; +export const getPostsError = (state) => state.posts.error; export const { postAdded, reactionAdded } = postsSlice.actions;