imgrewrite.tsx 11.1 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
10
11
12


export interface ImgState {
    state: MainimgType;
}
백승민's avatar
백승민 committed
13
14
15

export default function ImgRewrite() {
    // 이미지 수정
백승민's avatar
백승민 committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    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;

    const img = location.state;

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

백승민's avatar
백승민 committed
36
37
38
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");
    const [success, setSuccess] = useState(false);
백승민's avatar
백승민 committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
    const [file, setFile] = useState<File>();
    const [imageSrc, setImageSrc] = useState("");

    const PictureSrc = (fileBlob: Blob) => {
        const reader = new FileReader();

        reader.readAsDataURL(fileBlob);

        reader.onload = (data) => {
            if (typeof data.target?.result === "string") {
                console.log(data.target?.result);
                setImageSrc(data.target?.result);
            }
        };
    };

    const onUploadFile = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!(file === undefined)) {
            setFile(file);
            PictureSrc(file);
        }
    };
백승민's avatar
백승민 committed
62
63
64

    async function reWriteSubmit(event: FormEvent) {
        event.preventDefault();
백승민's avatar
백승민 committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
        if (confirm("수정하시겠습니까?") == true) {
            // try {
            setError("");
            console.log("user data", imgdata);
            // if (infoFormMatch(imgdata) === true) {
            // setLoading(true);
            // const res = await mainimgApi.updating(imgdata);
            // console.log("clear", res);
            // navigate("/admin", { replace: true });
            // setSuccess(true);
            // setError("");
            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);
백승민's avatar
백승민 committed
89
            }
백승민's avatar
백승민 committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
            else {
                formdata.append("updatemainimg","");
                console.log("formdata",formdata);
                const res = await mainimgApi.updateimg(formdata,imgdata._id);
                navigate("/admin", { replace: true });
                console.log("확인 중 ", res);
            }
            // }
            // } catch (error) {
            //     console.log("에러발생");
            //     catchErrors(error, setError);
            // } finally {
            //     setLoading(false);
            // }
        } else {
            return false;
백승민's avatar
백승민 committed
106
107
108
109
110
111
112
        }
    }
    // console.log(user._id)
    function infoFormMatch(pic: MainimgType) {
        if (!isLength(pic.title ?? "", { min: 1 })) {
            setError("제목을 입력해 주세요.");
            return false;
백승민's avatar
백승민 committed
113
        } else if (!isLength(pic.fileInfo.newfilename ?? "", { min: 1 })) {
백승민's avatar
백승민 committed
114
            setError("파일을 선택해 주세요.");
백승민's avatar
백승민 committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
            return false;
        } else if (equals(pic.city, "city")) {
            setError("도시를 선택해 주세요.");
            return false;
        } else if (equals(pic.theme, "theme")) {
            setError("테마를 선택해 주세요.");
            return false;
        } else {
            return true;
        }
    }


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

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

    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
151
    const fileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
백승민's avatar
백승민 committed
152
        const url = event.currentTarget.value;
백승민's avatar
백승민 committed
153
        const newUser = { ...imgdata, pic: { originalfilename: "", newfilename: url } };
백승민's avatar
백승민 committed
154
155
156
        setUrl(event.currentTarget.value);
        setImgData(newUser);
    };
백승민's avatar
백승민 committed
157
158
    return (
        <div>
백승민's avatar
백승민 committed
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
            <form onSubmit={reWriteSubmit} className="px-10 md:px-40">
                <table className="w-full ">
                    <thead></thead>
                    <tbody className=" border-separate border border-slate-400 ">
                        <tr >
                            <td className="border border-slate-300 min-w-max">
                                도시이름
                            </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">
                                테마이름
                            </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>
                            <td className="border border-slate-300">
                                url
                            </td>
                            <td>
백승민's avatar
백승민 committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
                                <input
                                    type="file"
                                    id="files"
                                    className="hidden"
                                    onChange={onUploadFile}
                                ></input>
                                <label htmlFor="files" className="border-2 m-5" >
                                    이미지 선택
                                </label>
                                {imageSrc ? (
                                    <img
                                        src={imageSrc}
                                        className="object-cover object-center h-full"
                                    />
                                ) : (
                                    <img
백승민's avatar
백승민 committed
236
                                        src={"http://localhost:3000/images/" + img.fileInfo.newfilename}
백승민's avatar
백승민 committed
237
238
239
                                        className="object-cover object-center h-full"
                                    />
                                )}
백승민's avatar
백승민 committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
                            </td>
                        </tr>
                        <tr>
                            <td className="border border-slate-300">
                                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-end">
                    <button type="submit" className="border-2">
                        수정
                    </button>
                    <button className="border-2">
                        <Link to={`/admin`}>
                            취소
                        </Link>
                    </button>
                </div>
            </form>
            <Outlet />
백승민's avatar
백승민 committed
267
268
269
        </div>
    );
};