/
vote.js
91 lines (77 loc) · 1.96 KB
/
vote.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import React, { Component } from 'react'
class Vote extends Component {
constructor(props) {
super(props);
this.state = {
votes: []
};
}
componentDidMount = () => {
this.hydrateWithLocalStorage();
window.addEventListener('beforeunload', this.saveToLocalStorage.bind(this));
};
componentWillUnmount = () => {
window.removeEventListener(
'beforeunload',
this.saveToLocalStorage.bind(this)
);
this.saveToLocalStorage();
};
hydrateWithLocalStorage = () => {
for (let key in this.state) {
if (localStorage.hasOwnProperty(key)) {
let value = localStorage.getItem(key);
try {
value = JSON.parse(value);
this.setState({ [key]: value });
} catch (e) {
this.setState({ [key]: value });
}
}
}
};
saveToLocalStorage = () => {
for (let key in this.state) {
localStorage.setItem(key, JSON.stringify(this.state[key]));
}
};
vote = (id, action, callback) => {
const votes = [...this.state.votes];
const updatedVotes = votes.filter(item => item.id !== id);
if (this.isVoted(id, action)) {
this.updateVotes(updatedVotes);
callback();
return;
}
updatedVotes.push({
id,
action
});
this.updateVotes(updatedVotes);
callback();
};
updateVotes = updatedVotes => {
this.setState({
votes: updatedVotes
});
};
isVoted = (id, action) => {
const votes = [...this.state.votes];
return votes.filter(item => item.id === id && item.action === action)
.length;
};
render = () => {
const { id, action, callback } = this.props;
return (
<button
onClick={() => this.vote(id, action, callback)}
className={`button is-primary is-fullwidth ${
this.isVoted(id, action) ? 'is-danger' : 'no-voted'
}`}
>
<i className={`fas fa-thumbs-${action}`} />
</button>
);
};
}
export default Vote;