Rev 2152 | Rev 2155 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useCallback, useMemo } from 'react'
import { useDispatch } from 'react-redux'
import { axios } from '@app/utils'
import { REACTIONS } from '@app/constants/feed'
import { addNotification } from '@app/redux/notification/notification.actions'
export default function withReactions(Component) {
const HOC = ({
saveUrl = '',
deleteUrl = '',
currentReactionType = null,
onReaction = () => null
}) => {
const dispatch = useDispatch()
const currentReaction = useMemo(
() => REACTIONS.find((r) => r.type === currentReactionType),
[currentReactionType]
)
const Icon = currentReaction ? currentReaction.icon : REACTIONS[0].icon
const saveReaction = useCallback(
(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 }))
}
onReaction({
reactions: data.reactions,
currentReactionType: type
})
})
},
[saveUrl, dispatch]
)
const deleteReaction = useCallback(() => {
axios.post(deleteUrl).then((res) => {
const { success, data } = res.data
if (!success) {
dispatch(addNotification({ style: 'danger', msg: data }))
return
}
onReaction({
reactions: data.reactions,
currentReactionType: ''
})
})
}, [])
return (
<Component
onClick={() =>
currentReaction ? deleteReaction() : saveReaction(REACTIONS[0].type)
}
>
{currentReaction ? (
<Icon style={{ color: currentReaction.color }} />
) : (
<Icon />
)}
{currentReaction ? currentReaction.label : 'Reaccionar'}
<div className='reactions'>
{REACTIONS.map(({ type, label, icon: Icon, color }) => (
<button
key={type}
title={label}
onClick={(e) => {
e.stopPropagation()
e.currentTarget.blur()
saveReaction(type)
}}
>
<Icon style={{ color }} />
</button>
))}
</div>
</Component>
)
}
return HOC
}