AutorÃa | Ultima modificación | Ver Log |
import React, { useEffect, useState } from 'react'
import { connect } from 'react-redux'
import { DeleteOutline } from '@mui/icons-material'
import { axios } from 'utils'
import { useOutsideClick } from '@hooks'
import { addNotification } from '@app/redux/notification/notification.actions'
const NotificationsOption = ({
addNotification,
Icon,
title,
url,
notificationsCount,
setNotificationsCount
}) => {
const [notifications, setNotifications] = useState([])
const [displayMenu, setDisplayMenu] = useState(false)
const [menu] = useOutsideClick(() => setDisplayMenu(false))
const readNotification = (link_read, link_notification) => {
axios
.post(link_read)
.then(({ data }) =>
data.success
? window.open(link_notification, '_blank').focus()
: addNotification({ style: 'danger', msg: data.data })
)
}
const deleteNotification = (link_delete) => {
axios.post(link_delete).then(({ data }) => {
!data.success && addNotification({ style: 'danger', msg: data.data })
setNotificationsCount(notificationsCount - 1)
setNotifications(
notifications.filter(
(notification) => notification.link_delete !== link_delete
)
)
addNotification({ style: 'success', msg: data.data })
})
}
const handleNotifications = () => {
axios
.get('/notifications/unreads')
.then(({ data }) => {
if (data.success) {
const notifications = new Set(data.data.notifications)
setNotifications([...notifications])
}
})
.catch((err) => {
addNotification({
style: 'error',
msg: 'Disculpe, ha ocurrido un error buscando notificaciones'
})
console.log('>>: err > ', err)
})
}
const handleClick = (e) => {
if (window.innerWidth > 768) {
e.preventDefault()
setDisplayMenu(!displayMenu)
}
}
useEffect(() => {
handleNotifications()
}, [notificationsCount])
return (
<li ref={menu}>
<a
href={url}
className={`header__option mobile ${displayMenu && 'active'}`}
target='framename'
onClick={handleClick}
>
{Icon && <Icon className='header__option-icon' />}
<span>{title}</span>
<span
className={`badge ${notificationsCount ? 'd-block' : 'd-none'}`}
style={{ top: '10px' }}
>
{notificationsCount}
</span>
</a>
{!!notifications.length && (
<nav
className={`nav__options-dropdown d-none d-md-block ${
displayMenu && 'show'
}`}
style={{ maxHeight: '300px', overflow: 'auto' }}
>
<ul>
{notifications.map(
(
{ message, link_mark_read, link, link_delete, time_elapsed },
index
) => (
<li key={index}>
<div
className='d-flex align-items-center justify-content-between'
style={{ gap: '.5rem' }}
>
<a
href={link}
target='secondary'
onClick={(e) => {
e.preventDefault()
readNotification(link_mark_read, link)
}}
>
{message}
</a>
<DeleteOutline
onClick={() => deleteNotification(link_delete)}
/>
</div>
<small style={{ fontSize: '.85rem' }}>{time_elapsed}</small>
</li>
)
)}
</ul>
</nav>
)}
</li>
)
}
const mapDispatchToProps = {
addNotification: (notification) => addNotification(notification)
}
export default connect(null, mapDispatchToProps)(NotificationsOption)