step 17: use `canVote()` to prevent users from voting on posts they are not allowed to

This commit is contained in:
Pascal Precht 2019-02-18 13:55:03 +01:00
parent 98daae0660
commit 3dc492150b
No known key found for this signature in database
GPG Key ID: 0EE28D8D6FD85D7D
3 changed files with 39 additions and 6 deletions

View File

@ -29,11 +29,11 @@ export class App extends Component {
list = await Promise.all(list);
list = list.map((post, index) => {
post.id = index;
post.upvotes = parseInt(post.upvotes, 10);
post.downvotes = parseInt(post.downvotes, 10);
return post;
});
list;
this.setState({ posts: list });
}

View File

@ -8,8 +8,11 @@ export class List extends Component {
{this.props.posts.map(post => {
return (<Post
key={post.id}
id={post.id}
description={post.description}
creationDate={post.creationDate}
upvotes={post.upvotes}
downvotes={post.downvotes}
owner={post.owner}
/>)
})}

View File

@ -1,14 +1,25 @@
import React, { Component } from 'react';
import EmbarkJS from 'Embark/EmbarkJS';
import DReddit from 'Embark/contracts/DReddit';
import dateformat from 'dateformat';
const BALLOT = {
NONE: 0,
UPVOTE: 1,
DOWNVOTE: 2
};
export class Post extends Component {
constructor(props) {
super(props);
this.state = {
topic: '',
content: ''
content: '',
upvotes: this.props.upvotes,
downvotes: this.props.downvotes,
canVote: true,
submitting: false
};
}
@ -16,8 +27,26 @@ export class Post extends Component {
const ipfsHash = web3.utils.toAscii(this.props.description);
const data = await EmbarkJS.Storage.get(ipfsHash);
const { topic, content } = JSON.parse(data);
const canVote = await DReddit.methods.canVote(this.props.id).call();
this.setState({ topic, content });
this.setState({ topic, content, canVote });
}
async vote(ballot) {
const accounts = await web3.eth.getAccounts();
const vote = DReddit.methods.vote(this.props.id, ballot);
const estimate = await vote.estimateGas();
this.setState({ submitting: true });
await vote.send({from: accounts[0], gas: estimate + 1000});
this.setState({
upvotes: this.state.upvotes + (ballot == BALLOT.UPVOTE ? 1 : 0),
downvotes: this.state.downvotes + (ballot == BALLOT.DOWNVOTE ? 1 : 0),
canVote: false,
submitting: false
});
}
render() {
@ -25,14 +54,15 @@ export class Post extends Component {
new Date(this.props.creationDate * 1000),
'yyyy-mm-dd HH:MM:ss'
);
const disabled = this.state.submitting || !this.state.canVote;
return (
<React.Fragment>
<hr />
<h3>{this.state.topic}</h3>
<p>{this.state.content}</p>
<p><small><i>created at {formattedDate} by {this.props.owner}</i></small></p>
<button>Upvote</button>
<button>Downvote</button>
{this.state.upvotes} <button onClick={e => this.vote(BALLOT.UPVOTE)} disabled={disabled}>Upvote</button>
&nbsp;{this.state.downvotes} <button onClick={e => this.vote(BALLOT.DOWNVOTE)} disabled={disabled}>Downvote</button>
</React.Fragment>
)
}