admin.tsx 9 KB
Newer Older
백승민's avatar
백승민 committed
1
import { get } from "mongoose";
백승민's avatar
백승민 committed
2
import React, { FormEvent, useEffect, useState, MouseEvent } from "react";
백승민's avatar
백승민 committed
3
import { Link } from "react-router-dom";
백승민's avatar
백승민 committed
4
import { mainimgApi } from "../apis";
5
// import { profileUpload } from "../apis/profile.api";
백승민's avatar
백승민 committed
6
7
import { catchErrors } from "../helpers";
import { MainimgType } from "../types";
백승민's avatar
백승민 committed
8
import { MySlide } from "./adminslide";
백승민's avatar
백승민 committed
9

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

백승민's avatar
백승민 committed
14
export default function Admin() {
백승민's avatar
백승민 committed
15
16
    // 이미지 전체 불러오기
    const [getimgs, setGetimgs] = useState<MainimgType[]>([]);
백승민's avatar
백승민 committed
17

백승민's avatar
백승민 committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    async function imgsData() {
        const imgs = await mainimgApi.getmainimg();
        setGetimgs(imgs);
    }
    useEffect(() => {
        imgsData();
    }, []);
    // 이미지 추가하기
    const [addimg, setAddimg] = useState<MainimgType>({
        _id: "",
        theme: "",
        city: "",
        title: "",
        fileInfo: { originalfilename: "", newfilename: "" },
    });
백승민's avatar
백승민 committed
33

백승민's avatar
백승민 committed
34
35
36
37
38
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");
    const [addSuccess, setAddSuccess] = useState(false);
    const [delSuccess, setDelSuccess] = useState(false);
    const [file, setFile] = useState<File>();
백승민's avatar
백승민 committed
39

백승민's avatar
백승민 committed
40
41
42
43
44
45
46
47
48
    function handleSelectChange(event: React.ChangeEvent<HTMLSelectElement>) {
        const { name, value } = event.currentTarget;
        console.log(value);
        setAddimg({ ...addimg, [name]: value });
    }
    function handleInputeChange(event: React.ChangeEvent<HTMLInputElement>) {
        const { name, value } = event.currentTarget;
        setAddimg({ ...addimg, [name]: value });
    }
백승민's avatar
백승민 committed
49

백승민's avatar
백승민 committed
50
51
52
53
54
    function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
        const file = e.target.files?.[0];
        if (!(file === undefined)) {
            setFile(file);
        }
백승민's avatar
백승민 committed
55
    }
백승민's avatar
백승민 committed
56

백승민's avatar
백승민 committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    async function handleSubmit(event: FormEvent) {
        event.preventDefault();
        const formdata = new FormData();
        console.log(addimg);
        formdata.append("city", addimg.city);
        formdata.append("theme", addimg.theme);
        formdata.append("title", addimg.title);
        try {
            if (!(file === undefined)) {
                formdata.append("mainimg", file);
                console.log("fordata", formdata);
                const res = await mainimgApi.mainimg(formdata);
                console.log("확인 중 ", res);
                alert("img 추가되었습니다");
                setGetimgs([...getimgs, res])
            }
            else (
                console.log("file === undefined")
            )
        } catch (error) {
            console.log("에러발생");
            catchErrors(error, setError);
        } finally {
            setLoading(false);
        }
백승민's avatar
백승민 committed
82
    }
백승민's avatar
백승민 committed
83

백승민's avatar
백승민 committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

    // 이미지 삭제하기
    async function handleDeleteClick(event: MouseEvent<HTMLButtonElement>) {
        try {
            if (confirm("삭제하시겠습니까?") == true) {
                const picId = event.currentTarget.id;
                console.log("picId : ", picId);
                const res = await mainimgApi.delmainimg(picId);
                console.log("delete img", res);
                // setGetimgs(getimgs)
                setDelSuccess(true);
                setError("");
                alert("img 삭제되었습니다");
                const deleteimg = getimgs.filter(pic=>picId!==pic._id)
                setGetimgs(deleteimg)
            } else {
                return false;
            }
        } catch (error) {
            console.log("에러발생");
            catchErrors(error, setError);
        } finally {
            setLoading(false);
        }
백승민's avatar
백승민 committed
108
109
    }

백승민's avatar
백승민 committed
110
111
    let limit = 15;
    const numPages = Math.ceil(getimgs.length / 15);
백승민's avatar
백승민 committed
112

백승민's avatar
백승민 committed
113
114
    // const location = useLocation() as ImgState;
    // const img = location.state;
백승민's avatar
백승민 committed
115

백승민's avatar
백승민 committed
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
    const slides = [];
    for (let i = 0; i < numPages; i++) {
        const k = [
            getimgs
                .slice(i * limit, i * limit + limit)
                .map((picture, index: number) => (
                    <div key={index}>
                        <div className={`m-1 shrink-0 bg-gray-200 rounded shadow-md `}>
                            <img
                                src={"http://localhost:3000/images/" + picture.fileInfo.newfilename}
                                className="w-full h-10 md:h-20 object-center"
                            />
                            <p className="text-center text-xs">{picture.title}</p>
                        </div>
                        <div className="text-end">
                            <button className="border-r-2 border-r-indigo-500 text-xs">
                                <Link to={`/admin/${picture._id}`} state={picture}>
                                    수정
                                </Link>
                            </button>
                            <button
                                id={picture._id}
                                onClick={handleDeleteClick}
                                className="text-xs"
                            >
                                삭제
                            </button>
                        </div>
                    </div>
                )),
        ];
        slides.push(k);
    }
Kim, MinGyu's avatar
Kim, MinGyu committed
149

백승민's avatar
백승민 committed
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
    return (
        <div>
            <form onSubmit={handleSubmit}>
                <div className="flex flex-wrap justify-center gap-3">
                    <div className="gap-3 md:flex ">
                        <select
                            name="city"
                            id="Questions"
                            className="border border-3 border-black w-20 my-5"
                            defaultValue="질문종류"
                            onChange={handleSelectChange}
                        >
                            <option value="질문종류">도시</option>
                            <option value="Seoul">서울</option>
                            <option value="Busan">부산</option>
                            <option value="Incheon">인천</option>
                            <option value="Daegoo">대구</option>
                            <option value="Gwangjoo">광주</option>
                            <option value="Daejeon">대전</option>
                            <option value="Woolsan">울산</option>
                            <option value="Sejong">세종</option>
                            <option value="Dokdo">독도</option>
                            <option value="Jeju">제주</option>
                        </select>
                        <select
                            name="theme"
                            id="Questions"
                            className="border border-3 border-black w-20 my-5"
                            defaultValue="질문종류"
                            onChange={handleSelectChange}
                        >
                            <option value="질문종류">테마</option>
                            <option value="cycling">사이클링</option>
                            <option value="surfing">서핑</option>
                            <option value="activity">액티비티</option>
                            <option value="camping">캠핑</option>
                            <option value="skiing">스키</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 className="flex items-center justify-end gap-3">
                            <input
                                type="file"
                                id="files"
                                className="hidden"
                                onChange={handleFileChange}
                            ></input>
                            <label htmlFor="files" className="border-2 m-5">
                                이미지 선택
                            </label>
                        </div>
                        <div className="flex items-center justify-end gap-3 mt-2 md:mt-0">
                            <p>title :</p>
                            <input
                                name="title"
                                className="border-2 border-sky-500"
                                onChange={handleInputeChange}
                            />
                        </div>
                    </div>
                    <div className="my-5 flex items-center">
                        <button className="border-2 border-gray-500 rounded ">추가</button>
                    </div>
                </div>
            </form>
            <div className="flex justify-center">
                <MySlide key={Math.random()} slides={slides} />
백승민's avatar
백승민 committed
222
            </div>
백승민's avatar
백승민 committed
223
        </div>
백승민's avatar
백승민 committed
224
    );
Kim, MinGyu's avatar
Kim, MinGyu committed
225
}