Skip to content
Snippets Groups Projects
PostRead.js 4.44 KiB
Newer Older
import { useNavigate, useParams } from 'react-router-dom';
Gwangbin's avatar
Gwangbin committed
import React, { useEffect, useState, useContext } from 'react';
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
import Article from '../components/Article.js';
import { UserContext, ArticleContext } from '../Context.js';
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
import MapLocator from '../components/MapForLoaction.js';
import Comment from '../components/Comment.js';
import cookie from 'react-cookies';
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed

import axios from 'axios';
axios.defaults.withCredentials = true;

function PostRead() {
  let params = useParams();
  const userContext = useContext(UserContext);
  const articleContext = useContext(ArticleContext);
  const userinfo = cookie.load('name')
  const [article, setArticle] = useState(null)
  const [inputComment, setInputComment] = useState("")
  const [commentList, setCommentList] = useState("")
  const navigate = useNavigate();
Gwangbin's avatar
Gwangbin committed
  function MoveTo(link) {
    navigate(link)
Gwangbin's avatar
Gwangbin committed
  }
  useEffect(() => {
Gwangbin's avatar
Gwangbin committed
    console.log(userinfo);
    userContext.CheckSession()
Gwangbin's avatar
Gwangbin committed
      .then((response) => {
        if (!response.data) {
          alert("로그인 바랍니다.");
          MoveTo('/login');
        }
        else {
          return requestLoadArticleById(params.id)
        }
      })
      .then((response) => {
        console.log(response)
        setArticle(response.data)
      })
      .catch((response) => {
        console.log("error!:LogOut")
        console.log(response)
      })
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed

Gwangbin's avatar
Gwangbin committed
  }, []);
Gwangbin's avatar
Gwangbin committed
  function SetLike() {
Gwangbin's avatar
Gwangbin committed
    axios.put(`${process.env.REACT_APP_BACKEND_URL}/article/${params.id}/like`)
Gwangbin's avatar
Gwangbin committed
      .then(res => {
        return requestLoadArticleById(params.id)
      })
      .then(res => {
        setArticle(res.data)
      })
      .catch(err => {
        console.error(err);
      });
  const onTextChange = (e) => {
Gwangbin's avatar
Gwangbin committed
    const { value } = e.target;
    setInputComment(value);
  }
  const onSubmit = e => {
    e.preventDefault();
    if (!inputComment) {
      alert("댓글을 작성해주세요.");
      return
    }
Gwangbin's avatar
Gwangbin committed
    const data = { content: inputComment }
Gwangbin's avatar
Gwangbin committed
    axios.post(`${process.env.REACT_APP_BACKEND_URL}/article/${params.id}/comment`, data,
Gwangbin's avatar
Gwangbin committed
      {
        headers: { "Content-Type": 'application/json' }
      })
      .then(res => {
        return requestLoadArticleById(params.id)
      })
      .then(res => {
        setArticle(res.data)
      })
      .catch(err => {
        console.error(err);
      });
Gwangbin's avatar
Gwangbin committed
  function DelButton({ isThatYou, target }) {
    function deleteArticle() {
      console.log(target._id)
      requestDeleteArticleById(target._id).then(res => {
Gwangbin's avatar
Gwangbin committed
        alert("게시글이 삭제되었습니다");
Gwangbin's avatar
Gwangbin committed
        .catch(err => {
          console.error(err);
        });
Gwangbin's avatar
Gwangbin committed

Gwangbin's avatar
Gwangbin committed
      return (<button onClick={deleteArticle}>지우기</button>)
Gwangbin's avatar
Gwangbin committed

  if (article) {
Gwangbin's avatar
Gwangbin committed
    return (
Gwangbin's avatar
Gwangbin committed
        <div className="introduction" style={{ display: 'flex' }}>
          <MapLocator loc={{ lat: article.latitude, lng: article.longitude }} keyword={article.keyword}></MapLocator>
          <div>
            <Article data={article}></Article>
Gwangbin's avatar
Gwangbin committed
            <div style={{ display: 'flex' }}>
              <button onClick={SetLike}>좋아요</button>
Gwangbin's avatar
Gwangbin committed
              <DelButton isThatYou={userinfo.id === article.author._id} target={article}></DelButton>
Gwangbin's avatar
Gwangbin committed
            <ArticleContext.Provider value={{ requestLoadArticleById, setArticle }}>
              {
                article.comments.map((el) => {
                  return (
                    <Comment key={el._id} data={el}></Comment>
                  )
                })
              }
            </ArticleContext.Provider>
        <form onSubmit={onSubmit}>
Gwangbin's avatar
Gwangbin committed
          <div style={{ display: 'flex' }}>
            <button>댓글 작성</button>
            <input type="text" onChange={onTextChange}></input>
          </div>
Gwangbin's avatar
Gwangbin committed
        </form>
Gwangbin's avatar
Gwangbin committed
    )
Gwangbin's avatar
Gwangbin committed
    return (
      <div className="introduction" style={{ display: 'flex' }}>
        <p>로딩중입니다...</p>
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
  }
async function requestLoadArticleById(id) {
  const response = await axios({
Gwangbin's avatar
Gwangbin committed
    url: `${process.env.REACT_APP_BACKEND_URL}/article/${id}`, // 통신할 웹문서
    method: 'get', // 통신할 방식
  });
  return response;
}
async function requestDeleteArticleById(id) {
  const response = await axios({
Gwangbin's avatar
Gwangbin committed
    url: `${process.env.REACT_APP_BACKEND_URL}/article/${id}`, // 통신할 웹문서
    method: 'delete', // 통신할 방식
  });
  return response;
}

export default PostRead;