Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react';
- import fire from './config/Fire';
- class PostView extends Component{
- constructor(props){
- super(props);
- this.state = {
- title: props.selected_title,
- author: "",
- category: "",
- comments: [],
- date: "",
- post_text: "",
- views: -1,
- loaded: false,
- viewsUpdated:false,
- categoryViews:-1
- }
- }
- loadPost = () => {
- let x = this;
- fire.firestore().collection("posts").doc(x.state.title).get().then(function(doc){
- let author = doc.data().author_username;
- let category = doc.data().category;
- let comments = doc.data().comments;
- let date = doc.data().date;
- let post_text = doc.data().post_text;
- let views = doc.data().views;
- x.setState({
- author: author,
- category: category,
- comments: comments,
- date: date,
- post_text: post_text,
- views: views,
- });
- });
- if(this.state.category !== ""){
- let x = this;
- fire.firestore().collection("categories").doc(this.state.category).get().then(function(doc){
- let categoryViews = doc.data().totalviews;
- x.setState({
- categoryViews:categoryViews,
- loaded: true
- })
- });
- }
- }
- //Helper function called in displayPost()
- displayComments = (commentsMap) =>{
- commentsMap.map(i =>{
- return <li>{i}</li>
- })
- }
- displayPost = () =>{
- let commentsMap = [];
- for(let i=0; i<this.state.comments.length; i=i+2){
- commentsMap[i/2] = this.state.comments[i] + ": " + this.state.comments[i+1];
- }
- return (
- <div>
- <p>By: {this.state.author}</p>
- <p>Category: {this.state.category}</p>
- <p>Date: {this.state.date}</p>
- <p>Views: {this.state.views}</p>
- <h3>Post</h3>
- <br/>
- <p>{this.state.post_text}</p>
- <br/><br/>
- <p>Comments: </p>
- {this.displayComments(commentsMap)}
- </div>
- )
- }
- goBack = () =>{
- this.props.updateDisplayPosts(this.state.title);
- }
- incrementViews = () =>{
- let incrementViews = this.state.views + 1;
- this.setState({views:incrementViews});
- let postRef = fire.firestore().collection("posts").doc(this.state.title);
- postRef.set({
- author_username:x.state.author,
- category: x.state.category,
- comments:x.state.comments,
- date:x.state.date,
- post_text:x.state.post_text,
- views:incrementViews
- });
- let incrementCategoryViews = this.state.categoryViews + 1;
- this.setState({categoryViews:incrementCategoryViews});
- let categoryRef = fire.firestore().collection("categories").doc(this.state.category);
- categoryRef.set({
- totalviews:incrementCategoryViews
- });
- this.setState({viewsUpdated:true});
- }
- render(){
- return(
- <div>
- <h2>{this.state.title}</h2>
- <button onClick = {this.goBack}>Back</button>
- {this.loadPost()}
- {this.state.loaded ? this.displayPost() : null}
- {(!this.state.viewsUpdated && this.state.loaded) ? null : this.incrementViews()}
- </div>
- )
- }
- }
- export default PostView;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement