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

function Search(props) {
    const endPage = 10;
    const [state, setState] = useState(false);
    const [index, setIndex] = useState(1);
    const [showSet, setShowSet] = useState([false, false, false, false]);
    const [search, setSearch] = useState(queryString.parse(props.location.search).keyword);
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
18
    // const [pagePlace, setPagePlace] = useState();
Lee SeoYeon's avatar
merge    
Lee SeoYeon committed
19
20
    const [association, setAssociation] = useState([])
    const [pagePlace, setPagePlace] = useState([])
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
21
    const [bookmark, setBookmark] = useState([false, false, false, false])
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
22
    const user = isAuthenticated()
Lee SeoYeon's avatar
merge    
Lee SeoYeon committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

    // console.log("search###############", search)
    // const getPlace = () => {
    //     axios.get(`/api/search/places?keyword=${search}`)
    //         .then(res => {
    //             console.log("places=", res.data)
    //             // setPlace(res.data)
    //         })
    //         .catch(err => {
    //             console.log('search.places 에러 발생', err)
    //         })
    // }

    // const getImg = () => {
    //     axios.get(`/api/search/imges?keyword=${search}`)
    //         .then(res => {
    //             console.log("images=", res.data)
    //             // setImgUrl(res.data)
    //         })
    //         .catch(err => {
    //             console.log('search.images 에러 발생', err)
    //         })
    // }

    const getAssociation = () => {
        axios.get(`/api/search/association?keyword=${search}`)
            .then(res => {
                console.log("Associations = ", res.data)
                setAssociation(res.data)
            })
            .catch(err => {
                console.log("search.associations 에러 발생", err)
            })
    }



    useEffect(() => {
        getAssociation()
    }, []);

Lee SeoYeon's avatar
.    
Lee SeoYeon committed
64
65
66
67
    useEffect(() => {
        console.log("222222222222222222", bookmark)
    }, [bookmark])

Lee SeoYeon's avatar
merge    
Lee SeoYeon committed
68
69
    useEffect(() => {
        setPagePlace(paginate(association, index, association.length))
70
    }, [association]);
Lee SeoYeon's avatar
merge    
Lee SeoYeon committed
71
72
73
74

    useEffect(() => {
        getAssociation()
        if (state) {
Kim, Chaerin's avatar
.    
Kim, Chaerin committed
75
76
77
78
79
            // window.location.reload()
            // return <Redirect to={{
            //         pathname: `/search?keyword=${search}`,
            //         state: { id: search },
            //     }} />;
Lee SeoYeon's avatar
merge    
Lee SeoYeon committed
80
            props.history.push('/search?keyword=' + search)
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
81
            setState(false)
Kim, Chaerin's avatar
.    
Kim, Chaerin committed
82
            // console.log("search야", search)
83
84
        } window.addEventListener("scroll", infiniteScroll);
        return () => { window.removeEventListener("scroll", infiniteScroll); }
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
85
    }, [state]);
Lee SeoYeon's avatar
merge    
Lee SeoYeon committed
86

87
88
89
90
91
92
93
94
    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
95
        }
96
97
        console.log(scrollHeight, scrollTop, clientHeight)
    }
Lee SeoYeon's avatar
merge    
Lee SeoYeon committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
151
152
153
154
155


    const places = [{
        name: "한라산",
        address: "제주 서귀포시 토평동 산15-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?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",
    }]

    if (state !== false) {
        // 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}`} />;
    }

    const handlePage = (num) => {
        setIndex(num);
    }


    const handleChange = (e) => {
        setSearch(e.target.value);
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        setState(true);
    }

    function paginate(items, pageNumber, itemNumber) {
        const page = [];
        const startIndex = (pageNumber - 1) * itemNumber
        for (var i = 0; i < itemNumber; i++) {
            page.push(items[(startIndex + i)])
        }
        return page
    }

Lee SeoYeon's avatar
.    
Lee SeoYeon committed
156
    async function handlebookmark(index) {
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
157
        if (!bookmark[index]) {
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
158
159
160
            console.log(pagePlace[index])
            const response = await axios.put(`/api/users/bookmark?ID=${user}&place=${pagePlace[index]._id}`)
            alert(response.data, '북마크가 저장되었습니다.')
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
161
162
163
            const showArr = bookmark
            showArr[index] = true
            setBookmark(showArr)
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
164
            console.log("bookmark=", bookmark)
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
165
        } else {
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
166
167
            const response = await axios.delete(`/api/users/bookmark?ID=${user}&place=${pagePlace[index]._id}`)
            alert(response.data, '저장된 북마크가 삭제되었습니다.')
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
168
169
170
            const showArr = bookmark
            showArr[index] = false
            setBookmark(showArr)
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
171
            console.log("bookmark=", bookmark)
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
172
173
        }
    }
Lee SeoYeon's avatar
merge    
Lee SeoYeon committed
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


    let time = new Date()

    return (
        <Container >
            <Link to="/" className="d-flex justify-content-center"><Image src={ohuh} /></Link>
            <Row className="mb-2" className="d-flex justify-content-center">
                <Form style={{ width: "90vw" }} onSubmit={handleSubmit}>
                    <InputGroup size="lg">
                        <FormControl
                            placeholder="검색어를 입력하세요."
                            value={search}
                            aria-label="Large"
                            aria-describedby="inputGroup-sizing-sm"
                            onChange={handleChange}
                        />
                        <InputGroup.Append>
                            <Button type="submit" variant="outline-secondary" >검색</Button>
                        </InputGroup.Append>
                    </InputGroup>
                </Form>
            </Row>
            {time.toLocaleString()}
            <Row className="d-flex flex-wrap">
                {pagePlace.map((place, index) => {
                    return (
                        <Col key={index} md={6} >
                            <Card align="center" border="info" style={{ margin: "3%" }}>
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
203
204
205
206
207
208
209
210
211
212
213
214

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

export default Search;