step 15: create List component to render posts

This commit is contained in:
Pascal Precht 2019-02-14 16:01:53 +01:00
parent c6a4464bcf
commit 17509a9552
No known key found for this signature in database
GPG Key ID: 0EE28D8D6FD85D7D
3 changed files with 53 additions and 0 deletions

View File

@ -1,5 +1,6 @@
import React, { Component } from 'react';
import { CreatePost } from './CreatePost';
import { List } from './List';
export class App extends Component {
@ -8,6 +9,7 @@ export class App extends Component {
<React.Fragment>
<h1>DReddit</h1>
<CreatePost />
<List />
</React.Fragment>
)
}

47
app/js/components/List.js Normal file
View File

@ -0,0 +1,47 @@
import React, { Component } from 'react';
import EmbarkJS from 'Embark/EmbarkJS';
import DReddit from 'Embark/contracts/Dreddit';
import { Post } from './Post';
export class List extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
async componentDidMount() {
const totalPosts = await DReddit.methods.numPosts().call();
let list = [];
for (let i = 0; i < totalPosts; i++) {
const post = DReddit.methods.posts(i).call();
list.push(post);
}
list = await Promise.all(list);
list = list.map((post, index) => {
post.id = index;
return post;
});
this.setState({ posts: list });
}
render() {
return (<React.Fragment>
{this.state.posts.map(post => {
return (<Post
key={post.id}
description={post.description}
creationDate={post.creationDate}
owner={post.owner}
/>)
})}
</React.Fragment>
)
}
}

View File

@ -69,5 +69,9 @@ contract DReddit {
Post storage post = posts[_postId];
return uint8(post.voters[msg.sender]);
}
function numPosts() public view returns (uint) {
return posts.length;
}
}