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

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

백승민's avatar
백승민 committed
12
13
14
15
    async function imgsData() {
        const imgs = await mainimgApi.getmainimg();
        setGetimgs(imgs)
    };
백승민's avatar
백승민 committed
16

백승민's avatar
백승민 committed
17
18
19
20
    useEffect(() => {
        imgsData();
    }, []);

백승민's avatar
백승민 committed
21
    // 이미지 추가하기
백승민's avatar
백승민 committed
22
    const [addimg, setAddimg] = useState<MainimgType>({
백승민's avatar
백승민 committed
23
        _id: "",
백승민's avatar
백승민 committed
24
25
26
27
28
29
30
        theme: "",
        city: "",
        url: "",
        title: "",
    });
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");
백승민's avatar
백승민 committed
31
32
    const [addSuccess, setAddSuccess] = useState(false);
    const [delSuccess, setDelSuccess] = useState(false);
백승민's avatar
백승민 committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

    function handleSelectChange(event: React.ChangeEvent<HTMLSelectElement>) {
        const { name, value } = event.currentTarget;
        setAddimg({ ...addimg, [name]: value });
    }
    function handleInputeChange(event: React.ChangeEvent<HTMLInputElement>) {
        const { name, value } = event.currentTarget;
        setAddimg({ ...addimg, [name]: value });
    }

    async function handleSubmit(event: FormEvent) {
        event.preventDefault();
        try {
            setError("");
            console.log("img data", addimg);
            setLoading(true);
            const res = await mainimgApi.mainimg(addimg);
            console.log("서버연결됬나요", res);
백승민's avatar
백승민 committed
51
            setAddSuccess(true);
백승민's avatar
백승민 committed
52
53
54
55
56
57
58
59
60
            setError("");
        } catch (error) {
            console.log("에러발생");
            catchErrors(error, setError);
        } finally {
            setLoading(false);
        }
    }

백승민's avatar
백승민 committed
61
62
63
64
    if (addSuccess) {
        alert("img 추가되었습니다");
    }
    // 이미지 삭제하기
백승민's avatar
백승민 committed
65
    async function handleDeleteClick(event: MouseEvent<HTMLButtonElement>) {
백승민's avatar
백승민 committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
        try {
            if (confirm("삭제하시겠습니까?") == true) {
                const picId = event.currentTarget.id;
                console.log("picId : ", picId)
                const res = await mainimgApi.delmainimg(picId);
                console.log("delete img", res);
                setDelSuccess(true);
                setError("");
            } else {
                return false;
            }
        }
        catch (error) {
            console.log("에러발생");
            catchErrors(error, setError);
        } finally {
            setLoading(false);
        };
백승민's avatar
백승민 committed
84
    };
백승민's avatar
백승민 committed
85
86
87
    if (delSuccess) {
        alert("img 삭제되었습니다");
    }
백승민's avatar
백승민 committed
88

백승민's avatar
백승민 committed
89
90
91
92
93
94
95
    let limit = 15;
    const numPages = Math.ceil(getimgs.length / 15);

    const slides = []
    for (let i = 0; i < numPages; i++) {
        const k = [
            getimgs.slice(i * limit, i * limit + limit).map((pic, index: number) => (
백승민's avatar
백승민 committed
96
97
98
99
100
101
102
103
                <div key={index}>
                    <div className={`m-1 shrink-0 bg-gray-200 rounded shadow-md `}>
                        <img
                            src={pic.url}
                            className="w-full h-10 md:h-20 object-center"
                        />
                        <p className="text-center text-xs">{pic.title}</p>
                    </div>
백승민's avatar
백승민 committed
104
105
106
107
108
109
110
111
112
113
                    <div className="text-end">
                        <button className="border-r-2 border-r-indigo-500 text-xs">
                            <Link to="/rewrite">
                                수정
                            </Link>
                        </button>
                        <button id={pic._id} onClick={handleDeleteClick} className="text-xs">
                            삭제
                        </button>
                    </div>
백승민's avatar
백승민 committed
114
115
116
117
118
                </div>
            ))]
        slides.push(k);
    }

백승민's avatar
백승민 committed
119
120
121
122
    return (
        <div>
            <form
                onSubmit={handleSubmit}>
백승민's avatar
백승민 committed
123
124
125
126
127
128
129
130
131
132
                <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>
백승민's avatar
백승민 committed
133
134
135
136
137
138
139
140
141
142
                            <option value="서울">서울</option>
                            <option value="부산">부산</option>
                            <option value="인천">인천</option>
                            <option value="대구">대구</option>
                            <option value="광주">광주</option>
                            <option value="대전">대전</option>
                            <option value="울산">울산</option>
                            <option value="세종">세종</option>
                            <option value="독도">독도</option>
                            <option value="제주">제주</option>
백승민's avatar
백승민 committed
143
144
145
146
147
148
149
150
151
                        </select>
                        <select
                            name="theme"
                            id="Questions"
                            className="border border-3 border-black w-20 my-5"
                            defaultValue="질문종류"
                            onChange={handleSelectChange}
                        >
                            <option value="질문종류">테마</option>
백승민's avatar
백승민 committed
152
153
154
155
156
157
158
159
160
161
162
163
                            <option value="사이클링">사이클링</option>
                            <option value="서핑">서핑</option>
                            <option value="액티비티">액티비티</option>
                            <option value="캠핑">캠핑</option>
                            <option value="스키">스키</option>
                            <option value="보트">보트</option>
                            <option value="사막">사막</option>
                            <option value="골프">골프</option>
                            <option value="동굴">동굴</option>
                            <option value="문화재">문화재</option>
                            <option value="동물원">동물원</option>
                            <option value="사이클링">사이클링</option>
백승민's avatar
백승민 committed
164
165
166
167
168
169
170
171
172
173
174
175
                        </select>
                        <div className="flex items-center justify-end gap-3">
                            <p>url :</p>
                            <input name="url" className="border-2 border-sky-500"
                                onChange={handleInputeChange} />
                            {/* type="file"/> */}
                        </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>
백승민's avatar
백승민 committed
176
                    </div>
백승민's avatar
백승민 committed
177
178
                    <div className="my-5 flex items-center">
                        <button className="border-2 border-gray-500 rounded ">추가</button>
백승민's avatar
백승민 committed
179
180
181
                    </div>
                </div>
            </form>
백승민's avatar
백승민 committed
182
            <div className="flex justify-center">
백승민's avatar
백승민 committed
183
184
185
                <MySlide key={Math.random()}
                    slides={slides}
                />
백승민's avatar
백승민 committed
186

백승민's avatar
백승민 committed
187
            </div>
백승민's avatar
백승민 committed
188
189
190
        </div>
    );
};