import React, { Component } from 'react';
import ButtonClick from '../components/ButtonClick.js';
import ButtonModal from '../components/ButtonModal.js';
import { connect } from 'react-redux';
import { fetchProfile } from '../actions/buskers.js';
import PropTypes from 'prop-types';
class ButtonFan extends Component {
constructor(props) {
super(props);
this.state = {
fan: false,
isLogged: false,
likeNum: 0
}
this.submitFanRequest = this.submitFanRequest.bind(this);
this.stopBeignFan = this.stopBeignFan.bind(this);
}
UNSAFE_componentWillMount() {
const csrf = window._CONFIG_.csrf;
// if (csrf !== null && csrf !== "") {
this.setState({
fan: this.props.imFan,
// isLogged: true,
isLogged: csrf ? true : false,
likeNum: parseInt(this.props.likes)
})
// }
}
UNSAFE_componentWillReceiveProps(nextProps) {
const csrf = window._CONFIG_.csrf;
if (this.props.likes !== nextProps.likes
|| this.props.imFan !== nextProps.imFan) {
this.setState({
fan: nextProps.imFan,
likeNum: parseInt(nextProps.likes)
})
}
if (csrf !== null && csrf !== "") {
this.setState({
isLogged: true
})
}
}
submitFanRequest() {
const newState = { ...this.state };
const { uid, dispatch } = this.props;
const csrf = window._CONFIG_.csrf;
this.setState({
fan: !newState.fan,
likeNum: parseInt(newState.likeNum) + 1
});
fetch(`/api/v1/like/${uid}`, {
method: 'GET',
credentials: 'same-origin',
headers: { 'x-busk-csrf': csrf }
}).then(
response => response.json()
).then( json => dispatch(fetchProfile(uid, csrf))
.then(({user}) => {
this.setState({
fan: user.im_already_fan,
likeNum: parseInt(user.likes)
})
})
);
}
stopBeignFan() {
const newState = { ...this.state };
const { uid, dispatch } = this.props;
const csrf = window._CONFIG_.csrf;
this.setState({
likeNum: parseInt(newState.likeNum) - 1,
fan: !newState.fan
});
fetch(`/api/v1/unlike/${uid}`, {
method: 'GET',
credentials: 'same-origin',
headers: { 'x-busk-csrf': csrf }
}).then(
response => response.json()
).then( json => dispatch(fetchProfile(uid, csrf))
.then(({ user }) => {
this.setState({
fan: user.im_already_fan,
likeNum: parseInt(user.likes)
})
})
);
}
render() {
const { fan, likeNum, isLogged } = this.state;
const { disabled } = this.props;
return ( isLogged ?
:
)
}
}
ButtonFan.propTypes = {
disabled: PropTypes.bool,
dispatch: PropTypes.func,
imFan: PropTypes.bool/*.isRequired*/,
likes: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string
])/*.isRequired*/,
uid: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string
])/*.isRequired*/
}
export default connect()(ButtonFan);