Ajout du composant pour proposer des amis à l'utilisateur

master
Noan07 2 years ago
parent c11df0979d
commit 5483bd17ff

@ -2,12 +2,13 @@ import axios from "axios";
import { setPostError } from "../reducers/error.reducer";
import { setPostData, setPostLikeData, setPostUnLikeData } from "../reducers/post.reducer";
export const getPosts = () => {
export const getPosts = (num) => {
return (dispatch) => {
return axios
.get(`${process.env.REACT_APP_API_URL}api/post/`)
.then((res) => {
dispatch(setPostData(res.data));
const array = res.data.slice(0, num);
dispatch(setPostData(array));
})
.catch((err) => console.log(err))
}
@ -85,48 +86,48 @@ export const addPost = (data) => {
// };
// };
// export const addComment = (postId, commenterId, text, commenterPseudo) => {
// return (dispatch) => {
// return axios({
// method: "patch",
// url: `${process.env.REACT_APP_API_URL}api/post/comment-post/${postId}`,
// data: { commenterId, text, commenterPseudo },
// })
// .then((res) => {
// dispatch({ type: ADD_COMMENT, payload: { postId } });
// })
// .catch((err) => console.log(err));
// };
// };
// export const editComment = (postId, commentId, text) => {
// return (dispatch) => {
// return axios({
// method: "patch",
// url: `${process.env.REACT_APP_API_URL}api/post/edit-comment-post/${postId}`,
// data: { commentId, text },
// })
// .then((res) => {
// dispatch({ type: EDIT_COMMENT, payload: { postId, commentId, text } });
// })
// .catch((err) => console.log(err));
// };
// };
export const addComment = (postId, commenterId, text, commenterPseudo) => {
return (dispatch) => {
return axios({
method: "patch",
url: `${process.env.REACT_APP_API_URL}api/post/comment-post/${postId}`,
data: { commenterId, text, commenterPseudo },
})
.then((res) => {
// dispatch({ type: ADD_COMMENT, payload: { postId } });
})
.catch((err) => console.log(err));
};
};
// export const deleteComment = (postId, commentId) => {
// return (dispatch) => {
// return axios({
// method: "patch",
// url: `${process.env.REACT_APP_API_URL}api/post/delete-comment-post/${postId}`,
// data: { commentId },
// })
// .then((res) => {
// dispatch({ type: DELETE_COMMENT, payload: { postId, commentId } });
// })
// .catch((err) => console.log(err));
// };
// };
export const editComment = (postId, commentId, text) => {
return (dispatch) => {
return axios({
method: "patch",
url: `${process.env.REACT_APP_API_URL}api/post/edit-comment-post/${postId}`,
data: { commentId, text },
})
.then((res) => {
// dispatch({ type: EDIT_COMMENT, payload: { postId, commentId, text } });
})
.catch((err) => console.log(err));
};
};
export const deleteComment = (postId, commentId) => {
return (dispatch) => {
return axios({
method: "patch",
url: `${process.env.REACT_APP_API_URL}api/post/delete-comment-post/${postId}`,
data: { commentId },
})
.then((res) => {
//dispatch({ type: DELETE_COMMENT, payload: { postId, commentId } });
})
.catch((err) => console.log(err));
};
};
// export const getTrends = (sortedArray) => {
// return (dispatch) => {
// dispatch({ type: GET_TRENDS, payload: sortedArray });

@ -0,0 +1,67 @@
import React, { useContext, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { deleteComment } from '../../actions/post.actions';
import { UidContext } from '../AppContext';
const ActionComment = ( { commentaire , postId}) => {
const [createur, setCreateur] = useState(false);
const [edit, setEdit] = useState(false);
const [message,setMessage] = useState('');
const uid = useContext(UidContext);
const dispatch = useDispatch();
const handleEdit = (e) => {
e.preventDefault();
if(message){
//dispatch();
setMessage('');
setEdit(false);
}
};
const handleDelete = () => {
//dispatch(deleteComment(postId, commentaire._id))
};
useEffect(() => {
const verifCreateur = () => {
if(uid === commentaire.commenterId){
setCreateur(true);
}
}
verifCreateur();
}, [uid, commentaire.commenterId]);
return (
<div>
{createur && edit === false && (
<span onClick={() => setEdit(!edit)}>
<img src="" alt="editer"/>
</span>
)}
{createur && edit && (
<form action="" onSubmit={handleEdit}
className="edit-form">
<label htmlFor='text' onClick={() => setEdit(!edit)}>Modifier le commentaire</label>
<input type="text" name="text" onChange={(e) => setMessage(e.target.value)} defaultValue={commentaire.text}/>
<div>
<span onClick={() => {
if(window.confirm("Etes-vous sur de supprimer ce commentaire ?")){
handleDelete();
}
}}>
<img src="" alt="Icon supprimer"/>
</span>
</div>
<input type="submit" value="Modifier"/>
</form>
)}
</div>
);
};
export default ActionComment;

@ -0,0 +1,56 @@
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { addComment, getPosts } from '../../actions/post.actions';
import FollowHandler from '../UserProfil/FollowHandler';
import { isEmpty, timestampParser } from '../Utils';
import ActionComment from './ActionComment';
const Comment = ({ post }) => {
const [message, setMessage] = useState("");
const usersData = useSelector((state) => state.users.users);
const userData = useSelector((state) => state.user.user);
const dispatch = useDispatch();
const handleComment = (e) => {
e.preventDefault();
if (message) {
dispatch(addComment(post._id, userData._id, message, userData.pseudo))
.then(() => dispatch(getPosts()))
.then(() => setMessage(''));
}
};
return (
<div>
{post.comments.map((comment) => {
return (
<div className={comment.commenterId === userData._id ? "comment-friend" : "comment-user"} key={comment._id}>
<img id="PhotoProfile" alt="ppCommentaire" src={
!isEmpty(usersData[0]) &&
usersData.map((user) => {
if (user._id === comment.commenterId) return user.picture;
else return null;
}).join('')
}/>
<p>{comment.commenterPseudo}</p>
{comment.commenterPseudo !== userData._id && (
<FollowHandler idToFollow={comment.commenterId} type={'suggest'}/>)}
<span></span>
{timestampParser(comment.timestamp)}
<p>{comment.text}</p>
<ActionComment commentaire={comment} postId={post._Id} />
</div>
);
})}
{userData._id && (
<form action="" onSubmit={handleComment} className="form-comment">
<input type="text" name="text" onChange={(e) => setMessage(e.target.value)} value={message} placeholder="Ajoutez un commentaire" />
<input type="submit" value="Partager"/>
</form>
)}
</div>
);
};
export default Comment;

@ -1,7 +1,6 @@
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getPosts } from '../../actions/post.actions';
import NewPoste from '../NewPoste';
import { isEmpty } from "../Utils";
import Post from './Post';
@ -10,13 +9,22 @@ const DisplayPosts = () => {
const [count , setCount] = useState(5);
const dispatch = useDispatch();
const postsData = useSelector((state) => state.post.post);
const loadMore = () => {
if (window.innerHeight + document.documentElement.scrollTop + 1 > document.scrollingElement.scrollHeight){
setLoadPost(true);
}
}
useEffect(() => {
if (loadPost) {
dispatch(getPosts());
dispatch(getPosts(count));
setLoadPost(false);
setCount(count + 5);
}
}, [loadPost,dispatch])
window.addEventListener('scroll', loadMore);
return () => window.removeEventListener('scroll',loadMore);
}, [loadPost,dispatch,count])
return (
<div>

@ -4,6 +4,7 @@ import { useSelector } from 'react-redux';
import FollowHandler from '../UserProfil/FollowHandler';
import { dateParser, isEmpty } from '../Utils';
import ButtonLike from './ButtonLike';
import Comment from './Comment';
const LinkPreview = ({ link }) => {
@ -41,6 +42,10 @@ const Post = ( { post } ) => {
const [isLoading, setIsLoading] = useState(true);
const usersData = useSelector((state) => state.users.users);
const userData = useSelector((state) => state.user.user);
const [updated,setUpdate] = useState(false);
const [message, setMessage] = useState(null);
const [comments, setComments] = useState(false);
useEffect(() => {
!isEmpty(usersData[0]) && setIsLoading(false)
@ -89,10 +94,11 @@ const Post = ( { post } ) => {
<div>{post.likers.length}</div>
</div>
<div id="commentaire">
<img src="commentaire.png"/>
<img src="commentaire.png" onClick={() => setComments(!comments)}/>
<div>{post.comments.length}</div>
</div>
</div>
{comments && <Comment post={post} />}
</div>
</div>) }
</li>

@ -0,0 +1,79 @@
import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { isEmpty } from '../Utils';
import FollowHandler from './FollowHandler';
const SuggestFriends = () => {
// const userData = useSelector((state) => state.user.user);
// const usersData = useSelector((state) => state.users.users);
// const [chargement,setChargement] = useState(true);
// const [change, setChange] = useState(true);
// const [friends, setFriends] = useState([]);
// useEffect(() => {
// const stateFriend = () => {
// let array = [];
// usersData.map((user) => {
// if(user._id !== userData._id && user.followers.includes(userData._id)){
// return array.push(user._id);
// }
// })
// //mettre dans un ordre aléatoire
// array.sort(() => 0.5 - Math.random());
// if(window.innerHeight > 780){
// array.length = 5;
// }
// if(window.innerHeight > 720){
// array.length = 4;
// }
// if(window.innerHeight > 660){
// array.length = 3;
// }
// if(window.innerHeight > 600){
// array.length = 2;
// }
// if(window.innerHeight > 540){
// array.length = 1;
// }else {
// array.length = 0;
// }
// setFriends(array);
// }
// if(change && !isEmpty(usersData[0]) && !isEmpty(userData._id)){
// stateFriend();
// setChargement(false);
// setChange(false);
// }
// }, [userData, usersData, change])
// return (
// <div>
// <p>Suggestions</p>
// {chargement ? (
// <i className='fas fa-spinner fa-pulse'></i>
// ) : (
// <ul>
// {friends && friends.map((user) => {
// for(let i = 0; i < usersData.length; i++){
// if(user === usersData[i]._id){
// return (
// <li className='suggest-friend-card' key={user}>
// <img src={usersData[i].picture} alt="img"/>
// <p>{usersData[i].pseudo}</p>
// <FollowHandler idToFollow={usersData[i]._id} type={"card"}/>
// </li>
// );
// }
// }
// })}
// </ul>
// )}
// </div>
//);
};
export default SuggestFriends;

@ -22,6 +22,9 @@ export const dateParser = (num) => {
return date.toString();
};
export const timestampParser = (num) => {
let options = {
hour: "2-digit",

@ -1,9 +1,12 @@
import React from 'react';
import React, { useContext } from 'react';
import AjoutLien from '../components/AjoutLien';
import DisplayPosts from '../components/Post/DisplayPosts';
import Navbar from '../components/Navbar';
import SuggestFriends from '../components/UserProfil/SuggestFriends';
import { UidContext } from '../components/AppContext';
const Home = () => {
const uid = useContext(UidContext);
return (
<>
<Navbar />
@ -13,6 +16,7 @@ const Home = () => {
</div>
<div className="RightBar">
<AjoutLien/>
{uid && <SuggestFriends />}
</div>
</main>
</>

@ -5,6 +5,7 @@
width: 140px;
height: 50px;
text-align: center;
cursor: pointer;
}
.popup-profil-container {

@ -92,8 +92,9 @@ module.exports.likePost = async (req, res) => {
};
module.exports.unlikePost = async (req, res) => {
if (!ObjectID.isValid(req.params.id))
return res.status(400).send("ID unknown : " + req.params.id);
if (!ObjectID.isValid(req.params.id)) {
return res.status(400).send("ID unknown: " + req.params.id);
}
try {
await PostModel.findByIdAndUpdate(
@ -101,27 +102,52 @@ module.exports.unlikePost = async (req, res) => {
{
$pull: { likers: req.body.id },
},
{ new: true },
(err, docs) => {
if (err) return res.status(400).send(err);
}
{ new: true }
);
await UserModel.findByIdAndUpdate(
req.body.id,
{
$pull: { likes: req.params.id },
},
{ new: true },
(err, docs) => {
if (!err) return res.send(docs);
else return res.status(400).send(err);
}
{ new: true }
);
} catch (err) {
return res.status(400).send(err);
}
res.send({ message: "Post unliked" });
} catch (err) {
return res.status(400).send(err);
}
};
// module.exports.unlikePost = async (req, res) => {
// if (!ObjectID.isValid(req.params.id))
// return res.status(400).send("ID unknown : " + req.params.id);
// try {
// await PostModel.findByIdAndUpdate(
// req.params.id,
// {
// $pull: { likers: req.body.id },
// },
// { new: true },
// (err, docs) => {
// if (err) return res.status(400).send(err);
// }
// );
// await UserModel.findByIdAndUpdate(
// req.body.id,
// {
// $pull: { likes: req.params.id },
// },
// { new: true },
// (err, docs) => {
// if (!err) return res.send(docs);
// else return res.status(400).send(err);
// }
// );
// } catch (err) {
// return res.status(400).send(err);
// }
// };
module.exports.commentPost = (req, res) => {
if (!ObjectID.isValid(req.params.id))
return res.status(400).send("ID unknown : " + req.params.id);

@ -51,38 +51,63 @@ module.exports.deleteUser = async (req, res) => {
};
module.exports.follow = async (req, res) => {
if (
!ObjectID.isValid(req.params.id) ||
!ObjectID.isValid(req.body.idToFollow)
)
if (!ObjectID.isValid(req.params.id) || !ObjectID.isValid(req.body.idToFollow)) {
return res.status(400).send("ID unknown : " + req.params.id);
}
try {
// add to the follower list
await UserModel.findByIdAndUpdate(
const user = await UserModel.findByIdAndUpdate(
req.params.id,
{ $addToSet: { following: req.body.idToFollow }, },
{ new: true , upsert: true },
(err, docs) => {
if (!err) return res.send(docs);
else return res.status(200).send(err);
}
)
// ajouter à la liste des followers
await UserModel.findByIdAndUpdate(
req.body.idToFollow,
{ $addToSet: { followers: req.params.id }, },
{ new: true , upsert: true},
(err, docs) => {
if (!err) return res.send(docs);
else return res.status(200).send(err);
}
);
{ $addToSet: { following: req.body.idToFollow } },
{ new: true, upsert: true }
);
const userToFollow = await UserModel.findByIdAndUpdate(
req.body.idToFollow,
{ $addToSet: { followers: req.params.id } },
{ new: true, upsert: true }
);
res.send({ user, userToFollow });
} catch (err) {
return res.status(400).send(err);
}
};
// module.exports.follow = async (req, res) => {
// if (
// !ObjectID.isValid(req.params.id) ||
// !ObjectID.isValid(req.body.idToFollow)
// )
// return res.status(400).send("ID unknown : " + req.params.id);
// try {
// // add to the follower list
// await UserModel.findByIdAndUpdate(
// req.params.id,
// { $addToSet: { following: req.body.idToFollow }, },
// { new: true , upsert: true },
// (err, docs) => {
// if (!err) return res.send(docs);
// else return res.status(200).send(err);
// }
// )
// // ajouter à la liste des followers
// await UserModel.findByIdAndUpdate(
// req.body.idToFollow,
// { $addToSet: { followers: req.params.id }, },
// { new: true , upsert: true},
// (err, docs) => {
// if (!err) return res.send(docs);
// else return res.status(200).send(err);
// }
// );
// } catch (err) {
// return res.status(400).send(err);
// }
// };
module.exports.unfollow = async (req, res) => {
if (
!ObjectID.isValid(req.params.id) ||

Loading…
Cancel
Save