Skip to content

Commit

Permalink
Update Article from Front End
Browse files Browse the repository at this point in the history
  • Loading branch information
compmonk committed May 19, 2020
1 parent ded34f8 commit f587f46
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 180 deletions.
272 changes: 99 additions & 173 deletions src/components/article/Article.js
Original file line number Diff line number Diff line change
@@ -1,184 +1,110 @@
import React from "react";
import { useState, useEffect } from "react";
import { Form, Button, Col } from "react-bootstrap";
import Page404 from "../others/FourZeroFour";
import Rating from "react-rating";
import { useParams } from "react-router-dom";
import { AuthContext } from "../auth/AuthContext";
import React, {useContext} from "react";
import {useState, useEffect} from "react";
import {Form, Button, Col} from "react-bootstrap";
import {useParams} from "react-router-dom";
import {AuthContext} from "../auth/AuthContext";
import "../../sass/App.css";
import axios from "axios";
let updateArticle = {};
let flag = false;
let star = 0;
const Author = ({ article }) => {
return (
<Form className="col-sm-8 col-md-8 col-lg-8 counselor-form">
<Form.Group as={Col} controlId="formBasicEmail">
<Form.Text className="text-muted">
You can Update Article here.
</Form.Text>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Title </Form.Label>
<Form.Control
type="text"
placeholder={article.title}
onChange={(e) => (updateArticle.title = e.target.value)}
/>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Text</Form.Label>
<Form.Control
type="text"
placeholder={article.text}
onChange={(e) => (updateArticle.text = e.target.value)}
/>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>HTML</Form.Label>
<Form.Control
type="text"
placeholder={article.html}
onChange={(e) => (updateArticle.html = e.target.value)}
/>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Keywords</Form.Label>
<Form.Control
type="text"
placeholder={article.keywords}
onChange={(e) => (updateArticle.keywords = e.target.value.split(","))}
/>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Total Read</Form.Label>
<Form.Control disabled type="text" value={article.read} />
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Cost</Form.Label>
<Form.Control type="text" value={article.cost} />
</Form.Group>
<br />
{/* Rate this article -{" "}
<Rating
onClick={(value) => {
star = value;
}}
placeholderRating={star}
></Rating> */}
<Button
type="submit"
onClick={async (e) => {
{
console.log("updated values", updateArticle);
let uri = `/api/user/${article._id}/update`;
let res = await axios.put(uri, updateArticle);
if (res) alert("Updated");
e.preventDefault();
}
}}
>
Update
</Button>
</Form>
);
};

const NotAuthor = async ({ article, userState }) => {
return (
<Form className="col-sm-8 col-md-8 col-lg-8 counselor-form">
<Form.Group as={Col} controlId="formBasicEmail">
<Form.Text className="text-muted">
You can only read Article here.
</Form.Text>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Title</Form.Label>
<Form.Control type="text" value={article.title} disabled />
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Text</Form.Label>
<Form.Control disabled type="text" value={article.text} />
</Form.Group>
<Form.Group as={Col}>
<Form.Label>HTML</Form.Label>
<Form.Control disabled type="text" value={article.html} />
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Keywords</Form.Label>
<Form.Control disabled type="text" value={article.keywords} />
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Total Read</Form.Label>
<Form.Control disabled type="text" value={article.read} />
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Cost</Form.Label>
<Form.Control disabled type="text" value={article.cost} />
</Form.Group>
<br />
Rate this article -{" "}
<Rating
onClick={async (value) => {
star = value;

if (article && article.ratings.length) {
article.ratings.map((ratingObject) => {
if (ratingObject.reviewerId === userState._id) {
ratingObject.rating = value;
flag = true;
return;
}
});
} else if (!flag) {
let ratingObject = {
reviewerId: userState._id,
rating: value,
};
article.ratings[0] = ratingObject;
}
let sent = await axios.put(`/api/articles/${article._id}`, article);
if (sent) alert("Rating submitted");
else alert("Rating Submission Failed");
}}
placeholderRating={star}
></Rating>
</Form>
);
};

function Article() {
const [article, setArticle] = useState({});
var isAuthor = false;
var currentUser = null;
let { articleId } = useParams();
const {currentUser, cookies} = useContext(AuthContext)
const [article, setArticle] = useState({});
let {articleId} = useParams();
let isAuthor = false;
let userRating = {}

useEffect(() => {
async function fetchData() {
const {data} = await axios.get(`/api/articles/${articleId}`)
setArticle(data);
}

fetchData();
}, [])

const onSubmit = async (e) => {
e.preventDefault();
let updatedArticle = article;
const {title, text, html, keywords} = e.target.elements;
updatedArticle["title"] = title.value
updatedArticle["text"] = text.value
updatedArticle["html"] = html.value
updatedArticle["keywords"] = keywords.value.split(",")
console.log(updatedArticle)

if (isAuthor) {
const {data} = await axios.put(`/api/user/${updatedArticle._id}/update`, updatedArticle, {
withCredentials: true,
headers: cookies
})
}

useEffect(() => {
async function fetch() {
let art = (await axios.get(`/api/articles/${articleId}`)).data;
if (!art) alert("View Failed");
currentUser = (await axios.get("/api/user/detail")).data;
setArticle(art);
if (art.author === currentUser._id) {
isAuthor = true;
} else {
isAuthor = false;
}
window.location.href = "/articles/all";

// userRating & userRating.rating ? userRating.rating = rating.value : {} = {}
}

if (currentUser && article) {
isAuthor = article.author === currentUser._id
userRating = article.ratings ? article.ratings.filter((rating) => (rating.reviewerId === currentUser._id))[0] : {}
console.log("isAuthor", isAuthor)
console.log("userRating", userRating);
}
fetch();
}, []);

if (!article) return <Page404></Page404>;
return (
<Form className="container-fluid col-sm-8 col-md-8 col-lg-8 counselor-form" onSubmit={onSubmit}>
<Form.Group as={Col}>
<Form.Text className="text-muted">
{isAuthor ? "You can update the Article here." : "You can rate the Article here."}
</Form.Text>
</Form.Group>
<Form.Group as={Col} controlId="formGridTitle">
<Form.Label>Title </Form.Label>
<Form.Control disabled={!isAuthor} type="text" name="title" defaultValue={article.title}
/>

return (
<div className="row justify-content-center">
{/* {isAuthor ? NotAuthor : Author} */}
{isAuthor ? (
<Author article={article} />
) : (
<NotAuthor article={article} userState={currentUser} />
)}
</div>
);
</Form.Group>
<Form.Group as={Col} controlId="formGridText">
<Form.Label>Text</Form.Label>
<Form.Control disabled={!isAuthor} as="textarea" name="text" type="input" defaultValue={article.text}
/>
</Form.Group>
<Form.Group as={Col} controlId="formGridHtml">
<Form.Label>Html</Form.Label>
<Form.Control disabled={!isAuthor} as="textarea" name="html" defaultValue={article.html}
/>
</Form.Group>
<Form.Group as={Col} controlId="formGridKeywords">
<Form.Label>Keywords</Form.Label>
<Form.Control disabled={!isAuthor} as="textarea" name="keywords" defaultValue={article.keywords}
/>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Total Read</Form.Label>
<Form.Control disabled type="text" value={article.read}/>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Cost</Form.Label>
<Form.Control disabled type="text" value={article.cost}/>
</Form.Group>
{/*<Form.Row as={Col}>*/}
{/* <Form.Group as={Col}>*/}
{/* <Form.Label>Your Rating</Form.Label>*/}
{/* <Form.Group as={Col}><Rating*/}
{/* name="rating"*/}
{/* placeholderRating={userRating && userRating.rating ? userRating.rating : 0}/></Form.Group>*/}
{/* </Form.Group>*/}
{/* <Form.Group>*/}
{/* <Form.Label>Average Rating</Form.Label>*/}
{/* <Form.Group as={Col}><Rating readonly={true} placeholderRating={article.rating}/></Form.Group>*/}
{/* </Form.Group>*/}
{/*</Form.Row>*/}
<Button type="submit">
{isAuthor ? "Update" : "Rate"}
</Button>
</Form>
)
}

export default Article;
9 changes: 2 additions & 7 deletions src/server/data/articles.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,7 @@ async function get(articleId) {
}
}

async function updateByAuthor(
articleId,
updatedArticle,
updaterId,
partial = false
) {
async function updateByAuthor(articleId, updatedArticle, updaterId, partial = false) {
const error = new Error();
error.http_code = 200;
const errors = {};
Expand Down Expand Up @@ -261,7 +256,7 @@ async function update(articleId, updatedArticle, partial = false) {

try {
delete updatedArticle._id;
if (updatedArticle.hasOwnProperty("ratings") && Array.isArray(updatedArticle.ratings)) {
if (updatedArticle.hasOwnProperty("ratings") && Array.isArray(updatedArticle.ratings) && updatedArticle.ratings.length) {
let totalRating = 0;
for (var i = 0; i < updatedArticle.ratings.length; i++) {
totalRating = totalRating + updatedArticle.ratings[i].rating;
Expand Down

0 comments on commit f587f46

Please sign in to comment.