LikeButton.jsx 1.5 KB

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