Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 655 | Rev 970 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { addNotification } from '../../redux/notification/notification.actions'
import { Col, Container, Row } from 'react-bootstrap'
import { useHistory, useLocation, useParams } from 'react-router-dom'
import { axios, debounce, jsonToParams } from '../../utils'
import SearchIcon from '@mui/icons-material/Search'

import Input from 'components/UI/Input'
import Spinner from 'components/UI/Spinner'
import SearchItem from 'components/search/SearchItem'
import EmptySection from 'components/UI/EmptySection'
import FiltersSidebar from 'components/search/FiltersSidebar'
import CategoryFilter from 'components/search/CategoryFilter'
import LocationFilter from 'components/search/LocationFilter'
import PaginationComponent from 'components/UI/PaginationComponent'

const SearchPage = () => {
  const [entities, setEntities] = useState([])
  const [loading, setLoading] = useState(true)
  const [category, setCategory] = useState('user')
  const [entity, setEntity] = useState('')
  const [address, setAddress] = useState({})
  const [currentPage, setCurrentPage] = useState(1)
  const [pages, setPages] = useState(1)
  const labels = useSelector(({ intl }) => intl.labels)
  const { category: categoryParam } = useParams()
  const { search } = useLocation()
  const dispatch = useDispatch()
  const history = useHistory()

  const params = new URLSearchParams(search)
  const keyword = params.get('keyword')

  const searchEntities = (
    page = 1,
    keyword = '',
    category = 'user',
    address = {}
  ) => {
    setLoading(true)
    const urlParams = { page, keyword }
    Object.entries(address).forEach(([key, value]) => (urlParams[key] = value))

    const url = `/search/entity/${category}?${jsonToParams(urlParams)}`

    history.replace(url)

    axios
      .get(url)
      .then(({ data: responseData }) => {
        const { success, data } = responseData

        if (!success) {
          throw new Error(data)
        }

        setEntities(data.current.items)
        setPages(data.total.pages)
      })
      .catch((err) => {
        dispatch(addNotification({ style: 'danger', msg: err.message }))
      })
      .finally(() => setLoading(false))
  }

  const onSearch = debounce((value) => setEntity(value), 500)

  useEffect(() => {
    searchEntities(currentPage, entity, category, address)
  }, [entity, category, currentPage, address])

  useEffect(() => {
    setEntity(keyword)
    setCategory(categoryParam)
  }, [keyword, categoryParam])

  return (
    <>
      <Container as='main'>
        <Input
          icon={SearchIcon}
          onChange={(e) => onSearch(e.target.value)}
          defaultValue={entity}
          placeholder={labels.search}
        />
        <Row className='mt-3'>
          <Col as='aside' md='4'>
            <FiltersSidebar>
              <CategoryFilter
                onChange={(newCategory) => setCategory(newCategory)}
              />
              <LocationFilter
                onChange={(newAddress) => setAddress(newAddress)}
              />
            </FiltersSidebar>
          </Col>
          <Col as='section' md='8'>
            <div className='posts-section'>
              {loading && <Spinner />}
              {entities.length ? (
                entities.map((entity) => (
                  <SearchItem key={entity.id} {...entity} />
                ))
              ) : (
                <EmptySection message='No hay resultados' />
              )}
            </div>
            <PaginationComponent
              pages={pages}
              currentActivePage={currentPage}
              onChangePage={(newCurrentPage) => setCurrentPage(newCurrentPage)}
              isRow
            />
          </Col>
        </Row>
      </Container>
    </>
  )
}

export default SearchPage