dreambold

post widget

Dec 27th, 2022
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useEffect } from "react";
  2. import { useDispatch, useSelector } from "react-redux";
  3. import { setPosts } from "state";
  4. import PostWidget from "./PostWidget";
  5.  
  6. const PostsWidget = ({ userId, isProfile = false }) => {
  7.   const dispatch = useDispatch();
  8.   const posts = useSelector((state) => state.posts);
  9.   const token = useSelector((state) => state.token);
  10.  
  11.   const getPosts = async () => {
  12.     const response = await fetch("http://localhost:3001/posts", {
  13.       method: "GET",
  14.       headers: { Authorization: `Bearer ${token}` },
  15.     });
  16.     const data = await response.json();
  17.     data.sort((a, b)=>{ return  new Date(dateStr).getTime(a.createdAt) - new Date(dateStr).getTime(b.createdAt); })
  18.     dispatch(setPosts({ posts: data }));
  19.   };
  20.  
  21.   const getUserPosts = async () => {
  22.     const response = await fetch(
  23.       `http://localhost:3001/posts/${userId}/posts`,
  24.       {
  25.         method: "GET",
  26.         headers: { Authorization: `Bearer ${token}` },
  27.       }
  28.     );
  29.     const data = await response.json();
  30.     data.sort((a, b)=>{ return  new Date(dateStr).getTime(a.createdAt) - new Date(dateStr).getTime(b.createdAt); })
  31.     dispatch(setPosts({ posts: data }));
  32.   };
  33.  
  34.   useEffect(() => {
  35.     if (isProfile) {
  36.       getUserPosts();
  37.     } else {
  38.       getPosts();
  39.     }
  40.   }, []); // eslint-disable-line react-hooks/exhaustive-deps
  41.  
  42.   return (
  43.     <>
  44.       {posts.map(
  45.         ({
  46.           _id,
  47.           userId,
  48.           firstName,
  49.           lastName,
  50.           description,
  51.           location,
  52.           picturePath,
  53.           userPicturePath,
  54.           likes,
  55.           comments,
  56.           createdAt,
  57.         }) => (
  58.           <PostWidget
  59.             key={_id}
  60.             postId={_id}
  61.             postUserId={userId}
  62.             name={`${firstName} ${lastName}`}
  63.             description={description}
  64.             location={location}
  65.             picturePath={picturePath}
  66.             userPicturePath={userPicturePath}
  67.             likes={likes}
  68.             comments={comments}
  69.             createdAt={createdAt} // Pass the createdAt field as a prop to the PostWidget component
  70.           />
  71.         )
  72.       )}
  73.     </>
  74.   );
  75. };
  76.  
  77. export default PostsWidget;
Advertisement
Add Comment
Please, Sign In to add comment