imgrewrite.tsx 8.89 KB
Newer Older
백승민's avatar
백승민 committed
1
import React, { FormEvent, useState, useEffect } from "react";
백승민's avatar
백승민 committed
2
import { Link, Outlet, useNavigate, useLocation } from "react-router-dom";
백승민's avatar
백승민 committed
3
import { mainimgApi } from "../apis";
백승민's avatar
백승민 committed
4
5
import isLength from "validator/lib/isLength";
import equals from "validator/lib/equals";
백승민's avatar
백승민 committed
6
7
import { catchErrors } from "../helpers";
import { MainimgType } from "../types";
백승민's avatar
백승민 committed
8
9

export interface ImgState {
Lee Soobeom's avatar
Lee Soobeom committed
10
  state: MainimgType;
백승민's avatar
백승민 committed
11
}
백승민's avatar
백승민 committed
12
13

export default function ImgRewrite() {
Lee Soobeom's avatar
Lee Soobeom committed
14
15
16
17
18
19
20
  // 이미지 수정
  const [theme, setTheme] = useState<string>("질문종류");
  const [city, setCity] = useState<string>("질문종류");
  const [url, setUrl] = useState<string>("");
  const [title, setTitle] = useState<string>("");
  const navigate = useNavigate();
  const location = useLocation() as ImgState;
백승민's avatar
백승민 committed
21

Lee Soobeom's avatar
Lee Soobeom committed
22
  const img = location.state;
백승민's avatar
백승민 committed
23

Lee Soobeom's avatar
Lee Soobeom committed
24
25
26
27
28
29
30
31
32
33
  const [imgdata, setImgData] = useState<MainimgType>({
    _id: img._id,
    theme: img.theme,
    city: img.city,
    title: img.title,
    fileInfo: { originalfilename: "", newfilename: "" },
  });
  useEffect(() => {
    console.log("수정 전 : ", imgdata);
  }, []);
백승민's avatar
백승민 committed
34

Lee Soobeom's avatar
Lee Soobeom committed
35
36
37
38
39
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const [file, setFile] = useState<File>();
  const [imageSrc, setImageSrc] = useState("");
백승민's avatar
백승민 committed
40

Lee Soobeom's avatar
Lee Soobeom committed
41
42
  const PictureSrc = (fileBlob: Blob) => {
    const reader = new FileReader();
백승민's avatar
백승민 committed
43

Lee Soobeom's avatar
Lee Soobeom committed
44
    reader.readAsDataURL(fileBlob);
백승민's avatar
백승민 committed
45

Lee Soobeom's avatar
Lee Soobeom committed
46
47
48
49
50
    reader.onload = (data) => {
      if (typeof data.target?.result === "string") {
        console.log(data.target?.result);
        setImageSrc(data.target?.result);
      }
백승민's avatar
백승민 committed
51
    };
Lee Soobeom's avatar
Lee Soobeom committed
52
  };
백승민's avatar
백승민 committed
53

Lee Soobeom's avatar
Lee Soobeom committed
54
55
56
57
58
59
60
  const onUploadFile = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!(file === undefined)) {
      setFile(file);
      PictureSrc(file);
    }
  };
백승민's avatar
백승민 committed
61

Lee Soobeom's avatar
Lee Soobeom committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
  async function reWriteSubmit(event: FormEvent) {
    event.preventDefault();
    if (confirm("수정하시겠습니까?") == true) {
      setError("");
      console.log("user data", imgdata);
      const formdata = new FormData();
      formdata.append("id", imgdata._id);
      console.log(imgdata._id);
      formdata.append("city", imgdata.city);
      formdata.append("theme", imgdata.theme);
      formdata.append("title", imgdata.title);
      console.log(formdata);
      if (!(file === undefined)) {
        formdata.append("updatemainimg", file);
        console.log("formdata", formdata);
        const res = await mainimgApi.updateimg(formdata, imgdata._id);
        navigate("/admin", { replace: true });
        console.log("확인 중 ", res);
      } else {
        formdata.append("updatemainimg", "");
        console.log("formdata", formdata);
        const res = await mainimgApi.updateimg(formdata, imgdata._id);
        navigate("/admin", { replace: true });
        console.log("확인 중 ", res);
      }
    } else {
      return false;
백승민's avatar
백승민 committed
89
    }
Lee Soobeom's avatar
Lee Soobeom committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
  }
  // console.log(user._id)
  function infoFormMatch(pic: MainimgType) {
    if (!isLength(pic.title ?? "", { min: 1 })) {
      setError("제목을 입력해 주세요.");
      return false;
    } else if (!isLength(pic.fileInfo.newfilename ?? "", { min: 1 })) {
      setError("파일을 선택해 주세요.");
      return false;
    } else if (equals(pic.city, "city")) {
      setError("도시를 선택해 주세요.");
      return false;
    } else if (equals(pic.theme, "theme")) {
      setError("테마를 선택해 주세요.");
      return false;
    } else {
      return true;
백승민's avatar
백승민 committed
107
    }
Lee Soobeom's avatar
Lee Soobeom committed
108
  }
백승민's avatar
백승민 committed
109

Lee Soobeom's avatar
Lee Soobeom committed
110
111
112
113
114
115
116
  const cityChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const city = event.currentTarget.value;
    const newUser = { ...imgdata, city: city };
    console.log(event.currentTarget.value);
    setCity(event.currentTarget.value);
    setImgData(newUser);
  };
백승민's avatar
백승민 committed
117

Lee Soobeom's avatar
Lee Soobeom committed
118
119
120
121
122
123
124
  const themeChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const theme = event.currentTarget.value;
    const newUser = { ...imgdata, theme: theme };
    console.log(event.currentTarget.value);
    setTheme(event.currentTarget.value);
    setImgData(newUser);
  };
백승민's avatar
백승민 committed
125

Lee Soobeom's avatar
Lee Soobeom committed
126
127
128
129
130
131
  const titleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const title = event.currentTarget.value;
    const newUser = { ...imgdata, title: title };
    setTitle(event.currentTarget.value);
    setImgData(newUser);
  };
백승민's avatar
백승민 committed
132

Lee Soobeom's avatar
Lee Soobeom committed
133
134
135
136
137
  const fileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const url = event.currentTarget.value;
    const newUser = {
      ...imgdata,
      pic: { originalfilename: "", newfilename: url },
백승민's avatar
백승민 committed
138
    };
Lee Soobeom's avatar
Lee Soobeom committed
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
    setUrl(event.currentTarget.value);
    setImgData(newUser);
  };
  return (
    <div>
      <div className="bg-white md:shadow-lg rounded py-24">
        <form onSubmit={reWriteSubmit} className="px-3 md:px-25">
          <table className="m-auto">
            <thead></thead>
            <tbody>
              <tr>
                <td className="border border-slate-300 px-5">도시이름</td>
                <td>
                  <select
                    name="city"
                    className="border border-3 border-black"
                    onChange={cityChange}
                    defaultValue={img.city}
                  >
                    <option value="city">도시</option>
                    <option value="Seoul">서울</option>
                    <option value="Busan">부산</option>
                    <option value="Incheon">인천</option>
                    <option value="Daegoo">대구</option>
                    <option value="Kwangjoo">광주</option>
                    <option value="Daejeon">대전</option>
                    <option value="Woolsan">울산</option>
                    <option value="Sejong">세종</option>
                    <option value="Dokdo">독도</option>
                    <option value="Jeju">제주</option>
                  </select>
                </td>
              </tr>
              <tr>
                <td className="border border-slate-300 min-w-max px-5">
                  테마이름
                </td>
                <td>
                  <select
                    name="theme"
                    className="border border-3 border-black"
                    onChange={themeChange}
                    defaultValue={img.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>
                </td>
              </tr>
              <tr className="items-center border border-slate-300">
                <td className="min-w-max px-7">이미지</td>
                <td>
                  <input
                    type="file"
                    id="files"
                    className="hidden"
                    onChange={onUploadFile}
                  ></input>
                  <label htmlFor="files" className="border-2">
                    이미지 선택
                  </label>
                  {imageSrc ? (
                    <img
                      src={imageSrc}
                      className="object-cover object-center h-full"
                    />
                  ) : (
                    <img
                      src={
                        "http://localhost:3000/images/" +
                        img.fileInfo.newfilename
                      }
                      className="object-cover object-center max-w-lg max-h-36"
                    />
                  )}
                </td>
              </tr>
              <tr>
                <td className="border border-slate-300 min-w-max px-9">
                  title
                </td>
                <td>
                  <input
                    className="border-2 border-sky-500 rounded w-full"
                    onChange={titleChange}
                    defaultValue={img.title}
                  />
                </td>
              </tr>
            </tbody>
          </table>
          <div className="text-center pt-10 whitespace-nowrap">
            <button
              type="submit"
              className="border-2 sm:mr-3 md:mr-10 md:text-lg"
            >
              수정
            </button>
            <button className="border-2 sm:mr-3 md:mr-10 md:text-lg">
              <Link to={`/admin`}>취소</Link>
            </button>
          </div>
        </form>
        {/* <Outlet /> */}
      </div>
      <div className="bg-lime-100 h-12" />
    </div>
  );
}