Rev 1979 | Rev 2154 | 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].iconconst saveReaction = useCallback((type) => {const formData = new FormData()formData.append('reaction', type)axios.post(saveUrl, formData).then((res) => {const { success, data } = res.dataif (!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.dataif (!success) {dispatch(addNotification({ style: 'danger', msg: data }))return}onReaction({reactions: data.reactions,currentReactionType: ''})})}, [])return (<Componenticon={currentReaction ? (<Icon style={{ color: currentReaction.color }} />) : (<Icon />)}onClick={() =>currentReaction ? deleteReaction() : saveReaction(REACTIONS[0].type)}label={currentReaction ? currentReaction.label : 'Reaccionar'}><div className='reactions'>{REACTIONS.map(({ type, label, icon: Icon, color }) => (<buttonkey={type}title={label}onClick={(e) => {e.stopPropagation()e.currentTarget.blur()saveReaction(type)}}><Icon style={{ color }} /></button>))}</div></Component>)}return HOC}