Rev 2775 | AutorÃa | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { axios, debounce } from '../../../utils';
import { useOutsideClick } from '@hooks';
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 dispatch = useDispatch();
const [ref] = useOutsideClick(() => 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={ref}
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;