Search.js 10.2 KB
Newer Older
1
import React, { useState, useEffect } from 'react';
Kim, Chaerin's avatar
Kim, Chaerin committed
2
import { Link, Redirect } from 'react-router-dom';
Kim, Chaerin's avatar
?    
Kim, Chaerin committed
3
import ohuh from '../ohuh-sm.PNG';
Lee SeoYeon's avatar
0127    
Lee SeoYeon committed
4
import { Container, Form, Row, Col, Card, Image, InputGroup, FormControl, Button, Nav } from 'react-bootstrap';
Kim, Chaerin's avatar
?    
Kim, Chaerin committed
5
import Paginations from '../Components/Paginations';
baesangjune's avatar
.    
baesangjune committed
6
import axios from 'axios';
Lee SeoYeon's avatar
merge    
Lee SeoYeon committed
7
import queryString from 'query-string'
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
8
import * as Icon from 'react-bootstrap-icons';
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
9
import { isAuthenticated } from '../utils/auth';
Lee SeoYeon's avatar
0127    
Lee SeoYeon committed
10
import catchErrors from '../utils/catchErrors'
Kim, Chaerin's avatar
Kim, Chaerin committed
11
12

function Search(props) {
baesangjune's avatar
baesangjune committed
13

Kim, Chaerin's avatar
Kim, Chaerin committed
14
    const [state, setState] = useState(false);
15
    const [index, setIndex] = useState(1);
16
    const [showSet, setShowSet] = useState([false, false, false, false]);
Kim, Chaerin's avatar
Kim, Chaerin committed
17
    const [search, setSearch] = useState(queryString.parse(props.location.search).keyword);
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
18
    const [bookmark, setBookmark] = useState([false, false, false, false])
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
19
    const user = isAuthenticated()
20
    const [mobile, setMobile] = useState();
baesangjune's avatar
baesangjune committed
21
22
23
    const [association, setAssociation] = useState([{ name: " ", address: " ", img: " " }])
    const [pagePlace, setPagePlace] = useState([{ name: " ", address: " ", img: " " }, { name: " ", address: " ", img: " " }])
    const [endPage, setEndPage] = useState(1)
Lee SeoYeon's avatar
0127    
Lee SeoYeon committed
24
25
26
27
28
29
30
31
32
33
    const [error, setError] = useState('')

    async function getBookmark() {
        try {
            const response = await axios.get(`/api/users/bookmark?ID=${user}`)
            // setBookmark(response.data.bookmark)
        } catch (error) {
            catchErrors(error, setError)
        }
    }
baesangjune's avatar
.    
baesangjune committed
34

Kim, Chaerin's avatar
.    
Kim, Chaerin committed
35
    const getAssociation = () => {
Kim, Chaerin's avatar
Kim, Chaerin committed
36
        axios.get(`/api/search/association?keyword=${search}`)
Kim, Chaerin's avatar
.    
Kim, Chaerin committed
37
38
39
40
41
42
43
            .then(res => {
                console.log("Associations = ", res.data)
                setAssociation(res.data)
            })
            .catch(err => {
                console.log("search.associations 에러 발생", err)
            })
baesangjune's avatar
.    
baesangjune committed
44
45
    }

baesangjune's avatar
.    
baesangjune committed
46

47
48

    useEffect(() => {
baesangjune's avatar
.    
baesangjune committed
49
        getAssociation()
baesangjune's avatar
baesangjune committed
50
    }, []);
Kim, Chaerin's avatar
.    
Kim, Chaerin committed
51

baesangjune's avatar
baesangjune committed
52
    useEffect(() => {
baesangjune's avatar
baesangjune committed
53
54
55
56
57
58
59
60
        if (association.length < 3) {
            setPagePlace(paginate(association, index, association.length))
        }
        else {
            setPagePlace(paginate(association, index, 4))
        }
        console.log("뿌릴 data1", pagePlace)
        setEndPage(Math.floor((association.length / 4)))
61
        console.log("7489309484839", endPage)
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
62

baesangjune's avatar
baesangjune committed
63
    }, [association, index])
baesangjune's avatar
.    
baesangjune committed
64

baesangjune's avatar
baesangjune committed
65
66
    useEffect(() => {
        getAssociation()
Kim, Chaerin's avatar
.    
Kim, Chaerin committed
67
        if (state) {
Kim, Chaerin's avatar
.    
Kim, Chaerin committed
68
69
70
71
72
            // window.location.reload()
            // return <Redirect to={{
            //         pathname: `/search?keyword=${search}`,
            //         state: { id: search },
            //     }} />;
Kim, Chaerin's avatar
.    
Kim, Chaerin committed
73
            props.history.push('/search?keyword=' + search)
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
74
            setState(false)
Kim, Chaerin's avatar
.    
Kim, Chaerin committed
75
            // console.log("search야", search)
76
77
        } window.addEventListener("scroll", infiniteScroll);
        return () => { window.removeEventListener("scroll", infiniteScroll); }
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
78
    }, [state]);
baesangjune's avatar
baesangjune committed
79

80
81
82
83
84
85
86
87
    const infiniteScroll = () => {
        const { documentElement, body } = document;
        const scrollHeight = Math.max(documentElement.scrollHeight, body.scrollHeight);
        const scrollTop = Math.max(documentElement.scrollTop, body.scrollTop);
        const clientHeight = documentElement.clientHeight;
        if (scrollTop + clientHeight >= scrollHeight) {
            // getReview();
            console.log("더불러")
Kim, Chaerin's avatar
.    
Kim, Chaerin committed
88
        }
89
90
        console.log(scrollHeight, scrollTop, clientHeight)
    }
baesangjune's avatar
.    
baesangjune committed
91
92


93
    const places = [{
94
        name: "한라산",
95
        address: "제주 서귀포시 토평동 산15-1",
baesangjune's avatar
.    
baesangjune committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
        img: "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/KOCIS_Halla_Mountain_in_Jeju-do_%286387785543%29.jpg/269px-KOCIS_Halla_Mountain_in_Jeju-do_%286387785543%29.jpg?size=200x200",
    }, {
        name: "성산일출봉(sungsan)",
        address: "제주 서귀포시 성산읍 성산리 1",
        img: "https://www.jeju.go.kr/pub/site/geopark/images/sub/sub03/02%EC%A7%80%EC%A7%88%EB%A7%88%EC%9D%84%EC%9D%B4%EC%95%BC%EA%B8%B0/%EC%A7%80%EC%A7%88%EB%A7%88%EC%9D%84/%EC%A7%80%EC%A7%88%EB%A7%88%EC%9D%84_%EC%84%B1%EC%82%B0%EC%9D%BC%EC%B6%9C%EB%B4%89/1412402261.jpg?400/400",
    }, {
        name: "해녀의 집(haenyeo)",
        address: "제주 서귀포시 성산읍 한도로 141-13지번오조리 3 오조해녀의집",
        img: "https://mblogthumb-phinf.pstatic.net/MjAxNjExMTdfMTc0/MDAxNDc5MzU3ODU0ODQy.KZYXCjzsXT3rCsE4HXBfxyCg2buvluBvN_7NxVp7BSwg.loJc89d8JjGXdNCn-4yMd7aMWPjfrZn21TI9Hyzemkog.JPEG.icocam11/20161010_100205.jpg?type=w800",
    }, {
        name: "오설록 티 뮤지엄(osulloc)",
        address: "제주 서귀포시 안덕면 신화역사로 15 오설록지번서광리 1235-1 오설록",
        img: "https://cdnweb01.wikitree.co.kr/webdata/editor/202007/01/img_20200701143323_2ced7627.webp",
    }, {
        name: "오설록 티 뮤지엄(osulloc)",
        address: "제주 서귀포시 안덕면 신화역사로 15 오설록지번서광리 1235-1 오설록",
        img: "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/KOCIS_Halla_Mountain_in_Jeju-do_%286387785543%29.jpg/269px-KOCIS_Halla_Mountain_in_Jeju-do_%286387785543%29.jpg",
113
114
    }]

Kim, Chaerin's avatar
Kim, Chaerin committed
115
    if (state !== false) {
Kim, Chaerin's avatar
.    
Kim, Chaerin committed
116
117
118
119
120
121
122
123
        // console.log(queryString.parse(props.location.search))
        //  = {keyword:search}
        // return <Redirect to={{
        //     pathname: `/search?keyword=${search}`,
        //     state: { id: search },
        // }} />;
        // history.pushState(null, null, "?"+queryParams.toString());
        // return <Redirect to={`/search?keyword=${search}`} />;
124
    }
Kim, Chaerin's avatar
Kim, Chaerin committed
125

126
127
    const handlePage = (num) => {
        setIndex(num);
baesangjune's avatar
baesangjune committed
128
129
        console.log("pagenation num", num)
        console.log(index)
130
131
132
    }


Kim, Chaerin's avatar
Kim, Chaerin committed
133
134
135
    const handleChange = (e) => {
        setSearch(e.target.value);
    }
Kim, Chaerin's avatar
Kim, Chaerin committed
136

Kim, Chaerin's avatar
Kim, Chaerin committed
137
    const handleSubmit = (e) => {
Kim, Chaerin's avatar
.    
Kim, Chaerin committed
138
        e.preventDefault()
baesangjune's avatar
baesangjune committed
139
140
        setState(true)
        setIndex(1)
Kim, Chaerin's avatar
Kim, Chaerin committed
141
    }
142

Kim, Chaerin's avatar
Kim, Chaerin committed
143
    function paginate(items, pageNumber, itemNumber) {
144
        const page = [];
Kim, Chaerin's avatar
Kim, Chaerin committed
145
146
        const startIndex = (pageNumber - 1) * itemNumber
        for (var i = 0; i < itemNumber; i++) {
baesangjune's avatar
baesangjune committed
147

148
149
            page.push(items[(startIndex + i)])
        }
baesangjune's avatar
baesangjune committed
150
        console.log("뿌릴 data22222222222222222", page)
151
152
        return page
    }
baesangjune's avatar
baesangjune committed
153
    //usestate 쓰거나 한번에 useeffect에 넣기
Lee SeoYeon's avatar
merge    
Lee SeoYeon committed
154

Lee SeoYeon's avatar
.    
Lee SeoYeon committed
155
    async function handlebookmark(index) {
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
156
        if (!bookmark[index]) {
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
157
            console.log(pagePlace[index])
Lee SeoYeon's avatar
0127    
Lee SeoYeon committed
158
159
160
161
162
163
            try {
                const response = await axios.put(`/api/users/bookmark?ID=${user}&place=${pagePlace[index]._id}`)
                alert(response.data, '북마크가 저장되었습니다.')
                const showArr = bookmark
                showArr[index] = true
                setBookmark(showArr)
164
                console.log("bookmark=", bookmark)
Lee SeoYeon's avatar
0127    
Lee SeoYeon committed
165
166
167
            } catch (error) {
                catchErrors(error, setError)
            }
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
168
        } else {
Lee SeoYeon's avatar
0127    
Lee SeoYeon committed
169
170
171
172
173
174
175
176
177
178
            try {
                const response = await axios.delete(`/api/users/bookmark?ID=${user}&place=${pagePlace[index]._id}`)
                alert(response.data, '저장된 북마크가 삭제되었습니다.')
                const showArr = bookmark
                showArr[index] = false
                setBookmark(showArr)
                console.log("bookmark=", bookmark)
            } catch (error) {
                catchErrors(error, setError)
            }
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
179
180
        }
    }
Lee SeoYeon's avatar
merge    
Lee SeoYeon committed
181

182

baesangjune's avatar
.    
baesangjune committed
183
    let time = new Date()
184

Kim, Chaerin's avatar
Kim, Chaerin committed
185
    return (
186
        <Container >
Kim, Chaerin's avatar
z    
Kim, Chaerin committed
187
            <Link to="/" className="d-flex justify-content-center"><Image src={ohuh} /></Link>
188
189
            <Row className="mb-2" className="d-flex justify-content-center">
                <Form style={{ width: "90vw" }} onSubmit={handleSubmit}>
190
191
192
193
194
195
196
197
198
                    <InputGroup size="lg">
                        <FormControl
                            placeholder="검색어를 입력하세요."
                            value={search}
                            aria-label="Large"
                            aria-describedby="inputGroup-sizing-sm"
                            onChange={handleChange}
                        />
                        <InputGroup.Append>
Kim, Chaerin's avatar
z    
Kim, Chaerin committed
199
                            <Button type="submit" variant="info" >검색</Button>
200
201
                        </InputGroup.Append>
                    </InputGroup>
202
                </Form>
Kim, Chaerin's avatar
Kim, Chaerin committed
203
            </Row>
204
            {/* {time.toLocaleString()} */}
205
            <Row className="d-flex flex-wrap">
baesangjune's avatar
baesangjune committed
206
207

                {console.log("#####################33", pagePlace)}
208
209
                {pagePlace.map((place, index) => {
                    return (
210
211
                        <Col key={index} md={6} >
                            <Card align="center" border="info" style={{ margin: "3%" }}>
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
212
213
214
215

                                <Card.Title className="d-flex justify-content-center" style={{ margin: "3%", fontSize: '200%', fontWeight: 'bold' }} >{place.name}
                                    {user ?
                                        <Button
Kim, Chaerin's avatar
z    
Kim, Chaerin committed
216
                                            variant={bookmark[index] ? "info" : "light"}
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
217
218
219
220
221
                                            onClick={() => handlebookmark(index, place)}>
                                            <Icon.BookmarkStarFill size={35} />
                                            {console.log("bookmark", bookmark)}
                                            {console.log("bookmark[index]", bookmark[index])}</Button> : null}
                                </Card.Title>
222
                                <Card.Img variant="top" style={{ padding: "5%", width: "100%", height: "340px" }} src={place.img} />
Kim, Chaerin's avatar
Kim, Chaerin committed
223
                                <Card.Body>
224
                                    <Card.Text style={{ overflow: 'auto', fontSize: '25px', width: '100%', height: "80px" }} >
225
                                        {place.address} </Card.Text>
Kim, Chaerin's avatar
Kim, Chaerin committed
226
                                    <Link to={`/place?id=${index}&place=${place.name}`} >
Kim, Chaerin's avatar
z    
Kim, Chaerin committed
227
                                        <Button variant="info"> {place.name} 자세히 살펴보기</Button>
Kim, Chaerin's avatar
Kim, Chaerin committed
228
                                    </Link>
229
230
231
                                </Card.Body>
                            </Card>
                        </Col>
232
233
234
                    )
                })}
            </Row>
235
            <Row className="mt-2 d-flex justify-content-center">
236
                <Paginations index={index} endPage={endPage} handlePage={handlePage}></Paginations>
237
            </Row>
Kim, Chaerin's avatar
Kim, Chaerin committed
238
        </Container >
Kim, Chaerin's avatar
Kim, Chaerin committed
239
240
241
    );
}

242
export default Search;