LikeButton.jsx 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { toastError } from '../util/apiNotification';
  4. import { withUnstatedContainers } from './UnstatedUtils';
  5. import AppContainer from '../services/AppContainer';
  6. class LikeButton extends React.Component {
  7. constructor(props) {
  8. super(props);
  9. this.state = {
  10. isLiked: props.isLiked,
  11. };
  12. this.handleClick = this.handleClick.bind(this);
  13. }
  14. async handleClick() {
  15. const { appContainer, pageId } = this.props;
  16. const bool = !this.state.isLiked;
  17. try {
  18. await appContainer.apiv3.put('/page/likes', { pageId, bool });
  19. this.setState({ isLiked: bool });
  20. }
  21. catch (err) {
  22. toastError(err);
  23. }
  24. }
  25. isUserLoggedIn() {
  26. return this.props.appContainer.currentUserId != null;
  27. }
  28. render() {
  29. // if guest user
  30. if (!this.isUserLoggedIn()) {
  31. return <div></div>;
  32. }
  33. return (
  34. <button
  35. type="button"
  36. onClick={this.handleClick}
  37. className={`btn rounded-circle btn-like border-0 d-edit-none
  38. ${this.state.isLiked ? 'active' : ''}`}
  39. >
  40. <i className="icon-like"></i>
  41. </button>
  42. );
  43. }
  44. }
  45. /**
  46. * Wrapper component for using unstated
  47. */
  48. const LikeButtonWrapper = withUnstatedContainers(LikeButton, [AppContainer]);
  49. LikeButton.propTypes = {
  50. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  51. pageId: PropTypes.string,
  52. isLiked: PropTypes.bool,
  53. size: PropTypes.string,
  54. };
  55. export default LikeButtonWrapper;