LikeButton.jsx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { toastError } from '../util/apiNotification';
  4. import { createSubscribedElement } 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-outline-info btn-like border-0 ${this.state.isLiked ? 'active' : ''}`}
  38. >
  39. <i className="icon-like"></i>
  40. </button>
  41. );
  42. }
  43. }
  44. /**
  45. * Wrapper component for using unstated
  46. */
  47. const LikeButtonWrapper = (props) => {
  48. return createSubscribedElement(LikeButton, props, [AppContainer]);
  49. };
  50. LikeButton.propTypes = {
  51. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  52. pageId: PropTypes.string,
  53. isLiked: PropTypes.bool,
  54. size: PropTypes.string,
  55. };
  56. export default LikeButtonWrapper;