Skip to content

Commit 5cc8502

Browse files
rehamdling like and getlikes to posts slice
1 parent 795b031 commit 5cc8502

File tree

6 files changed

+89
-64
lines changed

6 files changed

+89
-64
lines changed

src/Components/Home/HomeContent/HomeContent.jsx

+1-2
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import Posts from "../../Posts/Posts"
44

55

66
function HomeContent() {
7-
8-
7+
console.log('aaasdasd')
98
return (
109
<div className="w-1/2 h-full shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] min-h-[calc(100vh_-_99px)] bg-[rgba(252,250,248,1)]">
1110
<div className="w-full 2xl:w-[700px] 2xl:mx-auto !2xl:px-0 px-9">

src/Components/Posts/Post/Post.jsx

+11-39
Original file line numberDiff line numberDiff line change
@@ -6,52 +6,24 @@ import PostHeader from './PostHeader';
66
import useFetch from '../../../CustomHooks/useFetch'; // Import useFetch
77
import { getOptions } from '../../../options'; // Import getOptions
88
import CommentSection from './PostActions/comment/CommentSection';
9+
import { useDispatch, useSelector } from 'react-redux';
10+
import { fetchLikesForPost } from '../../../store/posts/fetchLikesForPost';
911

1012
function Post({ post }) {
11-
const [usersLikesThisPost, setUsersLikesThisPost] = useState([]);
12-
const [usersCommentsOnPost, setUsersCommentsOnPost] = useState([]);
13-
14-
const { fetchApi: getLikesData } = useFetch(`http://localhost:8000/api/posts/1/comments/likes`, getOptions);
15-
const { fetchApi: getCommentsData } = useFetch(`http://localhost:8000/api/posts/1/comments`, getOptions);
16-
17-
18-
const fetchComments = async () => {
19-
try {
20-
const resData = await getCommentsData();
21-
console.log(resData)
22-
if (resData.ok) {
23-
setUsersCommentsOnPost(resData.data.comments);
24-
}
25-
26-
} catch (error) {
27-
console.error('Error fetching comments:', error);
28-
}
29-
};
30-
useEffect(() => {
31-
const fetchLikes = async () => {
32-
try {
33-
const resData = await getLikesData();
34-
if (resData.ok) {
35-
setUsersLikesThisPost(resData.data.likeData);
36-
}
37-
} catch (error) {
38-
console.error('Error fetching likes:', error);
39-
}
40-
};
41-
42-
43-
44-
fetchLikes();
45-
fetchComments();
46-
}, []);
47-
13+
const dispatch=useDispatch()
14+
const likesDataForPost=useSelector(state=>state.posts).postsLikesData
15+
const existedPost=likesDataForPost.find(postData=>{
16+
return post.id==postData.postid})
17+
useEffect(()=>{
18+
dispatch(fetchLikesForPost(post.id))
19+
},[])
4820
return (
4921
<div className='py-[30px] border-t-[6px] border-t-[rgba(235,235,235,1)] font-medium'>
5022
<PostHeader post={post} />
5123
<div >
5224
<PostContent post={post} />
53-
<PostDetails post={post} />
54-
<PostActions post={post} usersLikesThisPost={usersLikesThisPost} />
25+
<PostDetails post={post} />
26+
<PostActions post={post} usersLikesThisPost={existedPost?existedPost.likesData:[]} />
5527
</div>
5628

5729
{/* {usersCommentsOnPost.length>0&& <CommentSection fetchedComments={usersCommentsOnPost} /> } */}
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,33 @@
1-
import { useState } from 'react';
2-
import { useEffect } from 'react';
3-
import likeIcon from '../../../../assets/images/posts/icons8-like-24 2.svg'
1+
import { useState, useEffect } from 'react';
2+
import likeIcon from '../../../../assets/images/posts/icons8-like-24 2.svg';
43
import useFetch from '../../../../CustomHooks/useFetch';
5-
import { postOptions } from '../../../../options';
4+
import { postOptions } from '../../../../options';
65

7-
const user_id=2;
8-
function LikeButton({post,usersLikesThisPost}) {
6+
const user_id = 2;
7+
8+
function LikeButton({ post, usersLikesThisPost }) {
99
const { fetchApi: likePost } = useFetch(`http://localhost:8000/api/posts/${post.id}/like`, postOptions);
10-
const [userLikedPost,setUserLikedPost]=useState(false)
10+
const [userLikedPost, setUserLikedPost] = useState(false);
11+
12+
13+
1114
useEffect(() => {
12-
const condition = usersLikesThisPost.some((like) => like.user_id === user_id)
13-
console.log(condition)
14-
setUserLikedPost(condition)
15-
},[])
16-
17-
const likePostHandler=async()=>{
18-
const resData=await likePost()
19-
if(resData.ok){
20-
setUserLikedPost(!userLikedPost)
21-
}
22-
}
15+
const condition = usersLikesThisPost.some((like) => like.user_id === user_id);
16+
setUserLikedPost(condition); }, [usersLikesThisPost]);
17+
18+
const likePostHandler = async () => {
19+
const resData = await likePost();
20+
if (resData.ok) {
21+
setUserLikedPost(!userLikedPost);
22+
}
23+
};
24+
2325
return (
24-
<button onClick={likePostHandler} className='flex flex-row-reverse items-center gap-2 ' ><img src={likeIcon} alt='like icon' className={`${userLikedPost?'invert-[0.5]':''} w-5`}/>Like</button>
25-
)
26+
<button onClick={likePostHandler} className='flex flex-row-reverse items-center gap-2'>
27+
<img src={likeIcon} alt='like icon' className={`${userLikedPost ? 'invert-[0.5]' : ''} w-5`} />
28+
Like
29+
</button>
30+
);
2631
}
2732

28-
export default LikeButton
33+
export default LikeButton;

src/Components/Posts/Posts.jsx

+2
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@ import {useSelector} from 'react-redux'
33

44
function Posts() {
55
const posts=useSelector(state=>state.posts).posts
6+
if(posts.length)
67
return (
78
<div >
89
{posts.map(post=><Post post={post} key={post.id}/>)}
910

1011
</div>
1112
)
13+
else return <></>
1214
}
1315

1416
export default Posts

src/store/posts/fetchLikesForPost.js

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/* eslint-disable no-useless-catch */
2+
import { createAsyncThunk } from '@reduxjs/toolkit';
3+
import { getOptions } from '../../options';
4+
5+
// Replace 'YOUR_API_ENDPOINT' with your actual API endpoint
6+
const API_ENDPOINT = 'http://localhost:8000/api/posts';
7+
8+
// Define the async thunk function
9+
export const fetchLikesForPost = createAsyncThunk(
10+
'posts/fetchLikesForPost',
11+
async (postId) => {
12+
try {
13+
const response = await fetch(`${API_ENDPOINT}/${postId}/likes`,getOptions('38|sum7kFXDl4oezUHHh6BgP6RhKAmdKPJ7YKGKK8bC'));
14+
if (!response.ok) {
15+
throw 'Failed to fetch likes data';
16+
}
17+
const resData = await response.json();
18+
return resData.data; // Return the fetched like data
19+
} catch (error) {
20+
return error;
21+
}
22+
}
23+
);

src/store/posts/postsSlice.js

+26-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { createSlice } from '@reduxjs/toolkit';
2+
import { fetchLikesForPost } from './fetchLikesForPost';
23

34
const postsSlice=createSlice({
45
name:'posts',
56
initialState:{
6-
posts:[]
7+
posts:[],
8+
postsLikesData:[]
79
},
810
reducers:{
911
setPosts:(state,action)=>{
@@ -30,8 +32,30 @@ const postsSlice=createSlice({
3032
return post
3133
}
3234
})
35+
},
36+
37+
},
38+
extraReducers: (builder) => {
39+
builder.addCase(fetchLikesForPost.fulfilled, (state, action) => {
40+
const fetchedData = action.payload.likeData;
41+
42+
if (fetchedData.length > 0) {
43+
const postId = fetchedData[0].post_id;
44+
45+
// Check if like data for the post already exists
46+
const existingPostLikeDataIndex = state.postsLikesData.findIndex((item) => item.postid === postId);
47+
48+
if (existingPostLikeDataIndex === -1) {
49+
// If it doesn't exist, add it to the state
50+
state.postsLikesData.push({ postid: postId, likesData: fetchedData });
51+
} else {
52+
// If it already exists, update the likesData for that post
53+
state.postsLikesData[existingPostLikeDataIndex].likesData = fetchedData;
3354
}
34-
}
55+
}
56+
57+
});
58+
},
3559
})
3660

3761
export const postsReducer=postsSlice.reducer

0 commit comments

Comments
 (0)