import { Fragment, useState, useEffect, useContext, useRef, useCallback } from 'react'; import Link from 'next/link'; import { UserContext } from '../../../contexts/UserContext'; import CommentCard from '../CommentCard/CommentCard'; import Loader from '../../Loader'; import api from '../../../utils/api'; import './FunctionComments.css'; const FunctionComments = ({ functionId }) => { // State pour poster un commentaire const { isAuth, user } = useContext(UserContext); const [inputState, setInputState] = useState({}); // State pour afficher les commentaires const [commentsData, setCommentsData] = useState({ hasMore: true, rows: [] }); const [isLoadingComments, setLoadingComments] = useState(true); const [pageComments, setPageComments] = useState(1); // Récupère les commentaires si la page change useEffect(() => { getCommentsData().then((data) => setCommentsData({ hasMore: data.hasMore, rows: [...commentsData.rows, ...data.rows] })); }, [pageComments]); // Permet la pagination au scroll const observer = useRef(); const lastCommentCardRef = useCallback((node) => { if (isLoadingComments) return; if (observer.current) observer.current.disconnect(); observer.current = new IntersectionObserver((entries) => { if (entries[0].isIntersecting && commentsData.hasMore) { setPageComments(pageComments + 1); } }, { threshold: 1 }); if (node) observer.current.observe(node); }, [isLoadingComments, commentsData.hasMore]); const getCommentsData = () => { setLoadingComments(true); return new Promise(async (next) => { const result = await api.get(`/comments/${functionId}/?page=${pageComments}&limit=10`); setLoadingComments(false); next(result.data); }); } const handleChange = (event) => { const inputStateNew = { ...inputState }; inputStateNew[event.target.name] = event.target.value; setInputState(inputStateNew); } const handleSubmit = async (event) => { setLoadingComments(true); event.preventDefault(); const token = user.token; if (isAuth && token != undefined && inputState.commentPost != undefined) { try { const response = await api.post(`/comments/${functionId}`, { message: inputState.commentPost }, { headers: { 'Authorization': token } }); const comment = { ...response.data, user: { name: user.name, logo: user.logo } }; setCommentsData({ hasMore: commentsData.hasMore, rows: [comment, ...commentsData.rows] }); setInputState({ commentPost: "" }); } catch { } } setLoadingComments(false); } return (
{ (isAuth) ?
:

Vous devez être connecté pour poster un commentaire.

}
{isLoadingComments &&
}
{commentsData.rows.map((comment, index) => { // Si c'est le dernier élément if (commentsData.rows.length === index + 1) { return ; } return ; })}
); } export default FunctionComments;