editpost.tsx 8.79 KB
Newer Older
Lee Soobeom's avatar
Lee Soobeom committed
1
import React, { FormEvent, useState } from "react";
Lee Soobeom's avatar
Lee Soobeom committed
2
3
4
5
6
7
8
9
10
import { useNavigate, useLocation } from "react-router-dom";
import isLength from "validator/lib/isLength";
import equals from "validator/lib/equals";
import { catchErrors } from "../helpers";
import { PostType } from "../types";
import { postApi } from "../apis";
import { PostState } from "./intopost";

export function EditPost() {
Lee Soobeom's avatar
Lee Soobeom committed
11
12
13
14
15
  const location = useLocation() as PostState;
  const post = location.state;

  const [city, setCity] = useState<string>(post.city);
  const [theme, setTheme] = useState<string>(post.theme);
Lee Soobeom's avatar
Lee Soobeom committed
16
17
  const [title, setTitle] = useState<string>("");
  const [text, setText] = useState<string>("");
Lee Soobeom's avatar
Lee Soobeom committed
18
19
  const [file, setFile] = useState<FileList>();
  const [imgSrc, setImgSrc] = useState<string[]>();
Lee Soobeom's avatar
Lee Soobeom committed
20
  const [change, setChange] = useState<boolean>(false);
Lee Soobeom's avatar
Lee Soobeom committed
21
22
23
24
25
26
27
28
29
  const navigate = useNavigate();

  const [user, setUser] = useState<PostType>({
    title: post.title,
    text: post.text,
    theme: post.theme,
    city: post.city,
    date: post.date,
    user: post.user,
Lee Soobeom's avatar
Lee Soobeom committed
30
    counts: post.counts,
Lee Soobeom's avatar
Lee Soobeom committed
31
    _id: post._id,
Lee Soobeom's avatar
Lee Soobeom committed
32
    file: post.file,
Lee Soobeom's avatar
Lee Soobeom committed
33
34
35
36
37
38
39
  });

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [disabled, setDisabled] = useState(false);
  const [success, setSuccess] = useState(false);

Lee Soobeom's avatar
Lee Soobeom committed
40
41
  const imgArr = new Array();

Lee Soobeom's avatar
Lee Soobeom committed
42
43
44
  // console.log("post.file", post.file);

  const updateImg2Db = async (filelist: FileList | undefined) => {
Lee Soobeom's avatar
Lee Soobeom committed
45
46
47
48
49
    const formdata = new FormData();
    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
50
    if (filelist === undefined) {
Lee Soobeom's avatar
Lee Soobeom committed
51
52
53
54
55
56
57
58
      const res = await postApi.updateImgAndPost(user._id, formdata);
    } else {
      for (var i = 0; i < filelist.length; i++) {
        formdata.append("picture", filelist?.[i]);
      }
      const res = await postApi.updateImgAndPost(user._id, formdata);
    }
  };
Lee Soobeom's avatar
Lee Soobeom committed
59

Lee Soobeom's avatar
Lee Soobeom committed
60
61
62
63
  async function reWriteSubmit(event: FormEvent) {
    event.preventDefault();
    try {
      if (confirm("게시물을 수정하시겠습니까?") == true) {
Lee Soobeom's avatar
Lee Soobeom committed
64
        setError("");
Lee Soobeom's avatar
Lee Soobeom committed
65
66
        if (postingFormMatch(user) === true) {
          setLoading(true);
Lee Soobeom's avatar
Lee Soobeom committed
67
68

          const res = updateImg2Db(file);
Lee Soobeom's avatar
Lee Soobeom committed
69
          navigate("/board", { replace: true });
Lee Soobeom's avatar
Lee Soobeom committed
70

Lee Soobeom's avatar
Lee Soobeom committed
71
72
73
74
75
          setSuccess(true);
          setError("");
        }
      } else {
        return false;
Lee Soobeom's avatar
Lee Soobeom committed
76
77
78
79
80
81
82
83
84
      }
    } catch (error) {
      console.log("에러발생");
      catchErrors(error, setError);
    } finally {
      setLoading(false);
    }
  }

Lee Soobeom's avatar
Lee Soobeom committed
85
  const handleInputPic = async (event: React.ChangeEvent<HTMLInputElement>) => {
Lee Soobeom's avatar
Lee Soobeom committed
86
    setChange(true);
Lee Soobeom's avatar
Lee Soobeom committed
87
88
89
    const maxImg = 10;
    const { files } = event.target;

Lee Soobeom's avatar
Lee Soobeom committed
90
91
    // console.log("update file", files);

Lee Soobeom's avatar
Lee Soobeom committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    if (!(files === null)) {
      setFile(files);
    }

    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);
          };
        }
      } else {
        alert(`사진은 최대 ${maxImg}장까지 업로드 가능합니다!`);
      }
    }
  };

Lee Soobeom's avatar
Lee Soobeom committed
113
  function postingFormMatch(user: PostType) {
Lee Soobeom's avatar
Lee Soobeom committed
114
    if (!isLength(user.title ?? "", { min: 1 })) {
Lee Soobeom's avatar
Lee Soobeom committed
115
      alert("제목을 입력해 주세요.");
Lee Soobeom's avatar
Lee Soobeom committed
116
      setError("제목을 입력해 주세요.");
Lee Soobeom's avatar
Lee Soobeom committed
117
118
      return false;
    } else if (!isLength(user.text ?? "", { min: 1 })) {
Lee Soobeom's avatar
Lee Soobeom committed
119
      alert("내용을 입력해 주세요.");
Lee Soobeom's avatar
Lee Soobeom committed
120
121
      setError("내용을 입력해 주세요.");
      return false;
Lee Soobeom's avatar
Lee Soobeom committed
122
    } else if (equals(city, "city")) {
Lee Soobeom's avatar
Lee Soobeom committed
123
      alert("도시를 선택해 주세요.");
Lee Soobeom's avatar
Lee Soobeom committed
124
      setError("도시를 선택해 주세요.");
Lee Soobeom's avatar
Lee Soobeom committed
125
      return false;
Lee Soobeom's avatar
Lee Soobeom committed
126
    } else if (equals(theme, "theme")) {
Lee Soobeom's avatar
Lee Soobeom committed
127
      alert("테마를 선택해 주세요.");
Lee Soobeom's avatar
Lee Soobeom committed
128
      setError("테마를 선택해 주세요.");
Lee Soobeom's avatar
Lee Soobeom committed
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
      return false;
    } else {
      return true;
    }
  }

  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);
  };

  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);
  };

  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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
  const oldFileShow = (post: PostType) => {
    const res = post.file?.map((file, i) => (
      <img
        key={i}
        src={"http://localhost:3000/images/" + file.newfilename}
        width={200}
        height={200}
      />
    ));
    // console.log("oldfiles", res);
    return res;
  };

  const newFileShow = (imgSrc: string[] | undefined) => {
    const res = imgSrc?.map((img, i) => (
      <img key={i} src={img} width={200} height={200} />
    ));
    return res;
  };

Lee Soobeom's avatar
Lee Soobeom committed
187
  return (
Kim, MinGyu's avatar
Kim, MinGyu committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    <form onSubmit={reWriteSubmit} className="flex flex-col  w-full">
      <div className="flex flex-row h-10 gap-x-1 justify-end">
        <div className="place-self-center w-16 h-6 border-2 border-sky-400  transition delay-150 bg-white-400 hover:-translate-y-1 hover:scale-110 hover:bg-gray-300 duration-300">
          <input
            id="files"
            type="file"
            multiple
            onChange={handleInputPic}
            className="hidden"
          />
          <label htmlFor="files" className="text-xs grid place-items-center">
            파일 선택
          </label>
        </div>
Lee Soobeom's avatar
Lee Soobeom committed
202

Kim, MinGyu's avatar
Kim, MinGyu committed
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
        <select
          name="city"
          className="border-2 border-sky-400  text-xs h-6 place-self-center"
          onChange={cityChange}
          defaultValue={post.city}
        >
          <option value="city">도시</option>
          <option value="Seoul">서울</option>
          <option value="Busan">부산</option>
          <option value="Incheon">인천</option>
          <option value="Daegu">대구</option>
          <option value="Gwangju">광주</option>
          <option value="Daejeon">대전</option>
          <option value="Woolsan">울산</option>
          <option value="Sejong">세종</option>
          <option value="Dokdo">독도</option>
          <option value="Jeju">제주</option>
        </select>
Lee Soobeom's avatar
Lee Soobeom committed
221

Kim, MinGyu's avatar
Kim, MinGyu committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
        <select
          name="theme"
          className="border-2 border-sky-400  text-xs h-6 place-self-center"
          onChange={themeChange}
          defaultValue={post.theme}
        >
          <option value="theme">테마</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>
Lee Soobeom's avatar
Lee Soobeom committed
242

Kim, MinGyu's avatar
Kim, MinGyu committed
243
244
245
246
247
248
249
        <button
          type="submit"
          className="h-6 w-10 place-self-center place-self-center border-2 border-sky-400   text-xs text-center transition delay-150 bg-white-400 hover:-translate-y-1 hover:scale-110 hover:bg-sky-300 duration-300"
        >
          수정
        </button>
      </div>
Lee Soobeom's avatar
Lee Soobeom committed
250

Kim, MinGyu's avatar
Kim, MinGyu committed
251
252
      <div className="flex flex-col w-full border-y-2 border-sky-500">
        <textarea
Lee Soobeom's avatar
Lee Soobeom committed
253
          defaultValue={post.title}
Kim, MinGyu's avatar
Kim, MinGyu committed
254
255
256
257
258
259
260
          name="title"
          onChange={titleChange}
          placeholder="제목을 입력해 주세요!"
          className="flex focus:outline-none"
        />
        <div className="flex flex-col mt-1 mb-1 border-t-2 border-sky-200">
          <div className="flex gap-x-2 h-44 overflow-x-auto ">
Lee Soobeom's avatar
Lee Soobeom committed
261
            {change ? newFileShow(imgSrc) : oldFileShow(post)}
Lee Soobeom's avatar
Lee Soobeom committed
262
          </div>
Lee Soobeom's avatar
Lee Soobeom committed
263
        </div>
Kim, MinGyu's avatar
Kim, MinGyu committed
264
        <textarea
Lee Soobeom's avatar
Lee Soobeom committed
265
          defaultValue={post.text}
Kim, MinGyu's avatar
Kim, MinGyu committed
266
267
268
269
270
271
272
          onChange={textChange}
          name="text"
          placeholder="여행 후기를 알려주세요!"
          className="flex h-44 border-t-2 border-sky-200 focus:outline-none "
        />
      </div>
    </form>
Lee Soobeom's avatar
Lee Soobeom committed
273
274
  );
}