diff --git a/components/Product/AddCommentToProduct.js b/components/Product/AddCommentToProduct.js new file mode 100644 index 0000000..599ec2a --- /dev/null +++ b/components/Product/AddCommentToProduct.js @@ -0,0 +1,89 @@ +import React, { useState } from 'react' +import axios from 'axios'; +import { Button, Comment, Form, Header, Message } from 'semantic-ui-react'; +import formatDate from '../../utils/formatDate'; +import catchErrors from '../../utils/catchErrors'; +import baseUrl from '../../utils/baseUrl'; +import cookie from 'js-cookie'; +import { useRouter } from 'next/router'; + +export default function AddCommentToProduct({ user, product, handleNewComment }) { + const [comment, setComment] = useState(''); + const [loading, setLoading] = useState(false); + const [success, setSuccess] = useState(false); + const [error, setError] = React.useState(""); + + const router = useRouter(); + + function handleChange(event) { + const { value } = event.target; + setComment(value); + } + + async function handleSubmit(event) { + event.preventDefault(); + if (!user) { + router.push('/login'); + return; + } + + try { + setLoading(true); + setError(""); + const url = `${baseUrl}/api/product`; + const token = cookie.get('token'); + const payload = { comment, productId: product._id }; + const headers = { Authorization: token }; + const response = await axios.put(url, payload, { headers }); + // { totalComments, product } + setComment(''); + handleNewComment(response.data); + setSuccess(true); + } catch (error) { + catchErrors(error, setError); + setSuccess(false); + } finally { + setLoading(false); + } + } + + return ( + <> + +
+ + + + { + user ? +