Rev 2134 | Rev 2153 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useRef, useState, useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { axios, debounce } from '../../../utils'
import useOutsideClick from '../../../hooks/useOutsideClick'
import { REACTIONS } from '@app/constants/feed'
import { addNotification } from '../../../redux/notification/notification.actions'
const ReactionsButton = ({
currentReaction,
onChange = () => null,
withLabel,
saveUrl,
deleteUrl,
...rest
}) => {
const [reaction, setReaction] = useState(null)
const [isHover, setIsHover] = useState(false)
const rectionBtn = useRef(null)
const dispatch = useDispatch()
useOutsideClick(rectionBtn, () => setIsHover(false))
const saveReaction = (type) => {
const formData = new FormData()
formData.append('reaction', type)
axios.post(saveUrl, formData).then((res) => {
const { success, data } = res.data
if (!success) {
dispatch(addNotification({ style: 'danger', msg: data }))
return
}
onChange(data)
})
}
const deleteReaction = () => {
axios.post(deleteUrl).then((res) => {
const { success, data } = res.data
if (!success) {
dispatch(addNotification({ style: 'danger', msg: data }))
return
}
setReaction(null)
onChange(data)
})
}
const onHover = debounce(() => setIsHover(true), 500)
const onUnhover = debounce(() => setIsHover(false), 500)
useEffect(() => {
const currentOption = REACTIONS.find(({ type }) => type === currentReaction)
currentOption ? setReaction(currentOption) : setReaction(null)
}, [currentReaction])
return (
<>
<button
{...rest}
onMouseOver={onHover}
onMouseOut={onUnhover}
ref={rectionBtn}
onClick={() =>
reaction.type !== 'default'
? deleteReaction()
: saveReaction(REACTIONS[0].type)
}
>
{reaction.icon}
{withLabel && reaction.label}
<div className={`reactions ${isHover ? 'active' : ''}`}>
{REACTIONS.map(({ icon: Icon, type, label, color }) => (
<button
key={type}
onClick={(e) => {
e.stopPropagation()
saveReaction(type)
}}
title={label}
>
<Icon style={{ color }} />
</button>
))}
</div>
</button>
</>
)
}
export default ReactionsButton