Proyectos de Subversion LeadersLinked - SPA

Rev

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

import React, { useCallback } from 'react'
import { useDispatch } from 'react-redux'
import { axios } from '../utils'
import { addNotification } from 'store/notification/notification.actions'
import { Recommend } from '@mui/icons-material'

import FunIcon from '../components/UI/icons/Fun'
import LoveItIcon from '../components/UI/icons/LoveIt'
import SupportIcon from '../components/UI/icons/Support'
import InterestIcon from '../components/UI/icons/Interest'
import RecommendIcon from '../components/UI/icons/Recommned'

const reactions = {
  r: {
    icon: RecommendIcon,
    label: 'Me gusta',
    type: 'r'
  },
  s: {
    icon: SupportIcon,
    label: 'Dar apoyo',
    type: 's'
  },
  l: {
    icon: LoveItIcon,
    label: 'Me encanta',
    type: 'l'
  },
  i: {
    icon: InterestIcon,
    label: 'Me interesa',
    type: 'i'
  },
  f: {
    icon: FunIcon,
    label: 'Me divierte',
    type: 'f'
  }
}

export default function withReactions(Component) {
  const HOC = ({
    saveUrl = '',
    deleteUrl = '',
    currentReaction = null,
    onReaction = () => null
  }) => {
    const dispatch = useDispatch()

    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,
            currentReaction: type
          })
        })
      },
      [saveUrl, dispatch, reactions]
    )

    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,
          currentReaction: ''
        })
      })
    }, [])

    return (
      <Component
        icon={currentReaction ? reactions[currentReaction].icon : Recommend}
        onClick={() =>
          currentReaction ? deleteReaction() : saveReaction(reactions.r.type)
        }
        label={
          currentReaction ? reactions[currentReaction].label : 'Reaccionar'
        }
      >
        <div className='reactions'>
          {Object.values(reactions).map(({ type, label, icon: Icon }) => (
            <button
              key={type}
              title={label}
              onClick={(e) => {
                e.stopPropagation()
                e.currentTarget.blur()
                saveReaction(type)
              }}
            >
              <Icon />
            </button>
          ))}
        </div>
      </Component>
    )
  }

  return HOC
}