posting.tsx 8.85 KB
Newer Older
Lee Soobeom's avatar
Lee Soobeom committed
1
import React, { FormEvent, useEffect, useState } from "react";
Lee Soobeom's avatar
Lee Soobeom committed
2
import { useNavigate } from "react-router-dom";
3
4
5
import isLength from "validator/lib/isLength";
import equals from "validator/lib/equals";
import { catchErrors } from "../helpers";
Lee Soobeom's avatar
Lee Soobeom committed
6
import { PostType } from "../types";
7
import { postApi } from "../apis";
Kim, MinGyu's avatar
Kim, MinGyu committed
8

9
export default function Posting() {
Lee Soobeom's avatar
Lee Soobeom committed
10
11
  const [city, setCity] = useState<string>("city");
  const [theme, setTheme] = useState<string>("theme");
12
13
  const [title, setTitle] = useState<string>("");
  const [text, setText] = useState<string>("");
Lee Soobeom's avatar
Lee Soobeom committed
14
  const [file, setFile] = useState<FileList>();
Lee Soobeom's avatar
Lee Soobeom committed
15
  const [imgSrc, setImgSrc] = useState<string[]>();
Lee Soobeom's avatar
Lee Soobeom committed
16
  const navigate = useNavigate();
Kim, MinGyu's avatar
Kim, MinGyu committed
17

Lee Soobeom's avatar
Lee Soobeom committed
18
  const [user, setUser] = useState<PostType>({
19
20
21
22
    title: "",
    text: "",
    theme: "",
    city: "",
Lee Soobeom's avatar
Lee Soobeom committed
23
24
    date: "",
    user: "",
Lee Soobeom's avatar
Lee Soobeom committed
25
    counts: 0,
Lee Soobeom's avatar
Lee Soobeom committed
26
    _id: "",
27
  });
Kim, MinGyu's avatar
Kim, MinGyu committed
28

29
30
31
32
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [disabled, setDisabled] = useState(false);
  const [success, setSuccess] = useState(false);
Kim, MinGyu's avatar
Kim, MinGyu committed
33

Lee Soobeom's avatar
Lee Soobeom committed
34
35
36
37
  const imgArr = new Array();

  const sendImg2Db = async (filelist: FileList) => {
    const formdata = new FormData();
Lee Soobeom's avatar
Lee Soobeom committed
38
39
40
41
    formdata.append("title", user.title);
    formdata.append("text", user.text);
    formdata.append("theme", user.theme);
    formdata.append("city", user.city);
Lee Soobeom's avatar
Lee Soobeom committed
42
    if (!(filelist === undefined || filelist === null)) {
Lee Soobeom's avatar
Lee Soobeom committed
43
44
45
46
47
48
49
50
51
      if (filelist.length === 1) {
        formdata.append("picture", filelist?.[0]);

        const res = await postApi.createFileAndPost(formdata);
      } else {
        for (var i = 0; i < filelist.length; i++) {
          formdata.append("picture", filelist?.[i]);
        }
        const res = await postApi.createFileAndPost(formdata);
Lee Soobeom's avatar
Lee Soobeom committed
52
53
54
55
      }
    }
  };

56
  async function handlePostSubmit(event: FormEvent) {
Lee Soobeom's avatar
Lee Soobeom committed
57
    event.preventDefault();
58
    try {
Lee Soobeom's avatar
Lee Soobeom committed
59
      if (confirm("게시물을 작성하시겠습니까?") == true) {
60
        setError("");
Lee Soobeom's avatar
Lee Soobeom committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
        // console.log("user data", user);
        if (!(imgSrc === undefined)) {
          if (postingFormMatch(user, imgSrc)) {
            setLoading(true);
            if (file) {
              const res = sendImg2Db(file);
              // console.log(res);
            }
          }
          navigate("/board", { replace: true });
          setSuccess(true);
          setError("");
        }
      } else {
        return false;
76
77
78
79
80
81
82
      }
    } catch (error) {
      console.log("에러발생");
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
Kim, MinGyu's avatar
Kim, MinGyu committed
83
84
  }

Lee Soobeom's avatar
Lee Soobeom committed
85
  function postingFormMatch(user: PostType, imgSrc: string[]) {
86
    if (!isLength(user.title ?? "", { min: 1 })) {
Lee Soobeom's avatar
Lee Soobeom committed
87
      alert("제목을 입력해 주세요.");
88
89
90
      setError("제목을 입력해 주세요.");
      return false;
    } else if (!isLength(user.text ?? "", { min: 1 })) {
Lee Soobeom's avatar
Lee Soobeom committed
91
      alert("내용을 입력해 주세요.");
92
93
      setError("내용을 입력해 주세요.");
      return false;
Lee Soobeom's avatar
Lee Soobeom committed
94
    } else if (equals(city, "city")) {
Lee Soobeom's avatar
Lee Soobeom committed
95
      alert("도시를 선택해 주세요.");
96
97
      setError("도시를 선택해 주세요.");
      return false;
Lee Soobeom's avatar
Lee Soobeom committed
98
    } else if (equals(theme, "theme")) {
Lee Soobeom's avatar
Lee Soobeom committed
99
      alert("테마를 선택해 주세요.");
Lee Soobeom's avatar
Lee Soobeom committed
100
101
      setError("테마를 선택해 주세요.");
      return false;
Lee Soobeom's avatar
Lee Soobeom committed
102
103
104
105
    } else if (imgSrc === undefined || imgSrc === null) {
      alert("사진을 첨부해 주세요.");
      setError("사진을 첨부해 주세요.");
      return false;
106
107
108
    } else {
      return true;
    }
Kim, MinGyu's avatar
Kim, MinGyu committed
109
110
  }

111
112
113
114
115
116
117
  const titleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    const title = event.currentTarget.value;
    const newUser = { ...user, title: title };
    console.log(event.currentTarget.value);
    setTitle(event.currentTarget.value);
    setUser(newUser);
  };
Kim, MinGyu's avatar
Kim, MinGyu committed
118

119
120
121
122
123
124
125
  const textChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    const text = event.currentTarget.value;
    const newUser = { ...user, text: text };
    console.log(event.currentTarget.value);
    setText(event.currentTarget.value);
    setUser(newUser);
  };
Kim, MinGyu's avatar
Kim, MinGyu committed
126

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
  const cityChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const city = event.currentTarget.value;
    const newUser = { ...user, city: city };
    console.log(event.currentTarget.value);
    setCity(event.currentTarget.value);
    setUser(newUser);
  };

  const themeChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const theme = event.currentTarget.value;
    const newUser = { ...user, theme: theme };
    console.log(event.currentTarget.value);
    setTheme(event.currentTarget.value);
    setUser(newUser);
  };
Lee Soobeom's avatar
Lee Soobeom committed
142

Lee Soobeom's avatar
Lee Soobeom committed
143
144
145
  const handleInputPic = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const maxImg = 10;
    const { files } = event.target;
Lee Soobeom's avatar
Lee Soobeom committed
146
147
148
149
150

    if (!(files === null)) {
      setFile(files);
    }

Lee Soobeom's avatar
Lee Soobeom committed
151
152
153
154
155
156
157
158
159
160
    if (!(files?.length === undefined)) {
      if (files?.length <= maxImg) {
        for (var i = 0; i < files.length; i++) {
          const reader = new FileReader();
          reader.readAsDataURL(files?.[i]);

          reader.onload = (e) => {
            imgArr.push(e.target?.result);
            setImgSrc(imgArr);
          };
Lee Soobeom's avatar
Lee Soobeom committed
161
162
        }
      } else {
Lee Soobeom's avatar
Lee Soobeom committed
163
        alert(`사진은 최대 ${maxImg}장까지 업로드 가능합니다!`);
Lee Soobeom's avatar
Lee Soobeom committed
164
165
166
167
      }
    }
  };

Kim, MinGyu's avatar
Kim, MinGyu committed
168
  return (
Lee Soobeom's avatar
Lee Soobeom committed
169
170
171
172
173
174
    <div className="flex place-content-center">
      <form
        onSubmit={handlePostSubmit}
        className="flex flex-col w-96 items-center"
      >
        <div className="flex flex-row h-8 gap-x-1">
Lee Soobeom's avatar
Lee Soobeom committed
175
          <div className="flex border-2 border-sky-400 rounded-full w-20 place-content-center transition delay-150 bg-white-400 hover:-translate-y-1 hover:scale-110 hover:bg-gray-300 duration-300">
Lee Soobeom's avatar
Lee Soobeom committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
            <input
              id="files"
              type="file"
              multiple
              onChange={handleInputPic}
              className="hidden"
            />
            <label htmlFor="files" className="text-xs text-center mt-1.5 ml-1 ">
              파일 선택
            </label>
          </div>

          <div className="flex w-20">
            <select
              name="city"
              className="border-2 border-sky-400 rounded-full w-20 text-xs"
              onChange={cityChange}
              defaultValue="질문종류"
            >
              <option value="질문종류">도시</option>
              <option value="Seoul">서울</option>
              <option value="Busan">부산</option>
              <option value="Incheon">인천</option>
Lee Soobeom's avatar
Lee Soobeom committed
199
200
              <option value="Daegu">대구</option>
              <option value="Gwangju">광주</option>
Lee Soobeom's avatar
Lee Soobeom committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
              <option value="Daejeon">대전</option>
              <option value="Woolsan">울산</option>
              <option value="Sejong">세종</option>
              <option value="Dokdo">독도</option>
              <option value="Jeju">제주</option>
            </select>
          </div>

          <div className="flex w-20">
            <select
              name="theme"
              className="border-2 border-sky-400 rounded-full w-20 text-xs"
              onChange={themeChange}
              defaultValue="질문종류"
            >
              <option value="질문종류">테마</option>
              <option value="cycling">사이클링</option>
              <option value="surfing">서핑</option>
              <option value="activity">액티비티</option>
              <option value="camping">캠핑</option>
              <option value="sking">스키</option>
              <option value="boat">보트</option>
              <option value="desert">사막</option>
              <option value="golf">골프</option>
              <option value="cave">동굴</option>
              <option value="history">문화재</option>
              <option value="zoo">동물원</option>
              <option value="cycling">사이클링</option>
            </select>
          </div>

          <div className="flex w-20">
            <button
              type="submit"
              className="border-2 border-sky-400 rounded-full w-20 text-xs text-center transition ease-in-out delay-150 bg-white-400 hover:-translate-y-1 hover:scale-110 hover:bg-sky-300 duration-300"
            >
              글쓰기
            </button>
Lee Soobeom's avatar
Lee Soobeom committed
239
          </div>
Kim, MinGyu's avatar
Kim, MinGyu committed
240
241
        </div>

Lee Soobeom's avatar
Lee Soobeom committed
242
        <div className="flex flex-col">
Kim, MinGyu's avatar
Kim, MinGyu committed
243
          <textarea
244
245
            name="title"
            onChange={titleChange}
Lee Soobeom's avatar
Lee Soobeom committed
246
247
248
249
250
251
252
253
254
            placeholder="제목을 입력해 주세요!"
            className="flex w-96 border-2 border-sky-500 rounded"
          />
          <div className="flex flex-col mt-1 mb-1">
            <div className="flex gap-x-2 h-48 overflow-x-scroll">
              {imgSrc?.map((img, i) => (
                <img key={i} src={img} width={200} height={200} />
              ))}
            </div>
Lee Soobeom's avatar
Lee Soobeom committed
255
          </div>
256
257
258
          <textarea
            onChange={textChange}
            name="text"
Lee Soobeom's avatar
Lee Soobeom committed
259
260
261
            placeholder="여행 후기를 알려주세요!"
            className="flex w-96 h-96 border-2 border-sky-500 rounded"
          />
Lee Soobeom's avatar
Lee Soobeom committed
262
        </div>
Kim, MinGyu's avatar
Kim, MinGyu committed
263
264
265
266
      </form>
    </div>
  );
}