Vulcan/packages/nova-base-components/lib/common/NewsletterButton.jsx

62 lines
2 KiB
React
Raw Normal View History

import { Components, registerComponent } from 'meteor/nova:lib';
import React, { PropTypes, Component } from 'react';
2016-06-09 20:26:33 +09:00
import { FormattedMessage } from 'react-intl';
import { Button } from 'react-bootstrap';
import { withMutation, withCurrentUser, withMessages } from 'meteor/nova:core';
class NewsletterButton extends Component {
constructor(props) {
super(props);
this.subscriptionAction = this.subscriptionAction.bind(this);
}
// use async/await + try/catch <=> promise.then(res => ..).catch(e => ...)
async subscriptionAction() {
const {
flash,
mutationName,
successCallback,
user,
[mutationName]: mutationToTrigger, // dynamic 'mutationToTrigger' variable based on the mutationName (addUserNewsletter or removeUserNewsletter)
} = this.props;
try {
const mutationResult = await mutationToTrigger({userId: user._id});
successCallback(mutationResult);
} catch(error) {
console.error(error); // eslint-disable-line no-console
flash(error.message, "error");
}
}
render() {
return (
<Button
className="newsletter-button"
2016-05-26 10:46:30 +02:00
onClick={this.subscriptionAction}
bsStyle="primary"
>
<FormattedMessage id={this.props.label}/>
</Button>
)
}
}
NewsletterButton.propTypes = {
mutationName: PropTypes.string.isRequired, // mutation to fire
label: PropTypes.string.isRequired, // label of the button
user: PropTypes.object.isRequired, // user to operate on
successCallback: PropTypes.func.isRequired, // what do to after the mutationName
addUserNewsletter: PropTypes.func.isRequired, // prop given by withMutation HOC
removeUserNewsletter: PropTypes.func.isRequired, // prop given by withMutation HOC
2016-11-15 18:33:16 +01:00
};
const addOptions = {name: 'addUserNewsletter', args: {userId: 'String'}};
const removeOptions = {name: 'removeUserNewsletter', args: {userId: 'String'}};
registerComponent('NewsletterButton', NewsletterButton, withCurrentUser, withMutation(addOptions), withMutation(removeOptions), withMessages);