BookmarkButton.jsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 btn-circle btn-outline-warning btn-bookmark border-0 ${`btn-${this.props.size}`} ${this.state.isBookmarked && 'active'}`}
  55. >
  56. <i className="icon-star"></i>
  57. </button>
  58. );
  59. }
  60. }
  61. BookmarkButton.propTypes = {
  62. pageId: PropTypes.string,
  63. crowi: PropTypes.object.isRequired,
  64. size: PropTypes.string,
  65. };
  66. BookmarkButton.defaultProps = {
  67. size: 'md',
  68. };
  69. export default BookmarkButton;