BookmarkButton.jsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { toastError } from '../util/apiNotification';
  4. class BookmarkButton extends React.Component {
  5. constructor(props) {
  6. super(props);
  7. this.state = {
  8. isBookmarked: false,
  9. };
  10. this.handleClick = this.handleClick.bind(this);
  11. }
  12. async componentDidMount() {
  13. const { pageId, crowi } = this.props;
  14. // if guest user
  15. if (!this.isUserLoggedIn()) {
  16. // do nothing
  17. return;
  18. }
  19. try {
  20. const response = await crowi.apiv3.get('/bookmarks', { pageId });
  21. if (response.data.bookmark != null) {
  22. this.setState({ isBookmarked: true });
  23. }
  24. }
  25. catch (err) {
  26. toastError(err);
  27. }
  28. }
  29. async handleClick() {
  30. const { crowi, pageId } = this.props;
  31. const bool = !this.state.isBookmarked;
  32. try {
  33. await crowi.apiv3.put('/bookmarks', { pageId, bool });
  34. this.setState({ isBookmarked: bool });
  35. }
  36. catch (err) {
  37. toastError(err);
  38. }
  39. }
  40. isUserLoggedIn() {
  41. return this.props.crowi.currentUserId != null;
  42. }
  43. render() {
  44. // if guest user
  45. if (!this.isUserLoggedIn()) {
  46. return <div></div>;
  47. }
  48. return (
  49. <button
  50. type="button"
  51. href="#"
  52. title="Bookmark"
  53. onClick={this.handleClick}
  54. className={`btn rounded-circle btn-bookmark border-0 d-edit-none
  55. ${`btn-${this.props.size}`}
  56. ${this.state.isBookmarked ? 'active' : ''}`}
  57. >
  58. <i className="icon-star"></i>
  59. </button>
  60. );
  61. }
  62. }
  63. BookmarkButton.propTypes = {
  64. pageId: PropTypes.string,
  65. crowi: PropTypes.object.isRequired,
  66. size: PropTypes.string,
  67. };
  68. BookmarkButton.defaultProps = {
  69. size: 'md',
  70. };
  71. export default BookmarkButton;