Compare commits

..

7 Commits

Author SHA1 Message Date
shobhitm23
b45fc3640c changed putPost function to see postID 2019-10-31 15:46:40 -04:00
shobhitm23
51fc965a90 changed variable name to postId 2019-10-31 15:29:54 -04:00
shobhitm23
a4b7f7a107 Added post.id in backend to display posts 2019-10-31 14:15:40 -04:00
7341de742e Fixing some issues with retrieving posts 2019-10-29 14:28:53 -04:00
shobhitm23
2fc37e3e34 Added link in index.js 2019-10-29 13:45:36 -04:00
shobhitm23
3f3a93be8c Added getAllPosts 2019-10-28 14:02:55 -04:00
shobhitm23
d6a0b0b1bc Displaying posts with image, time and content 2019-10-28 01:33:20 -04:00
15 changed files with 225 additions and 286 deletions

View File

@@ -1,24 +1,32 @@
/* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/always-return */
const admin = require('firebase-admin');
const { admin, db } = require("../util/admin");
exports.putPost = (req, res) => {
const newPost = {
body: req.body.body,
userHandle: req.user.handle,
userHandle: req.body.userHandle,
userImage: req.body.userImage,
userID: req.user.uid,
userID: req.userData.userID,
microBlogTitle: req.body.microBlogTitle,
createdAt: new Date().toISOString(),
likeCount: 0,
commentCount: 0,
microBlogTopics: req.body.microBlogTopics
};
const resPost;
admin.firestore().collection('posts').add(newPost)
.then((doc) => {
const resPost = newPost;
resPost = newPost;
resPost.postId = doc.id;
return admin.firestore().doc(`posts/${doc.id}`).set(resPost)
})
.then(() => {
return res.status(200).json(resPost);
})
.catch((err) => {
@@ -28,7 +36,7 @@ exports.putPost = (req, res) => {
};
exports.getallPostsforUser = (req, res) => {
admin.firestore().collection('posts').where('userHandle', '==', req.userData.handle ).get()
db.collection('posts').where('userHandle', '==', 'new user' ).get()
.then((data) => {
let posts = [];
data.forEach(function(doc) {
@@ -42,6 +50,29 @@ exports.getallPostsforUser = (req, res) => {
})
};
exports.getFilteredPosts = (req, res) => {
admin.firestore().collection('posts').where('userHandle', '==', 'new user').where('microBlogTopics', '==')
exports.getAllPosts = (req, res) => {
db.collection('posts')
.orderBy('createdAt', 'desc')
.get()
.then((data) => {
let posts = [];
data.forEach((doc) => {
posts.push({
body: doc.data().body,
userHandle: doc.data().userHandle,
createdAt: doc.data().createdAt,
commentCount: doc.data().commentCount,
likeCount: doc.data().likeCount,
userImage: doc.data().userImage,
microBlogTitle: doc.data().microBlogTitle,
microBlogTopics: doc.data().microBlogTopics,
postId: doc.id,
});
});
return res.status(200).json(posts);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
};

View File

@@ -1,5 +1,6 @@
/* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/always-return */
const { admin, db } = require("../util/admin");
const admin = require('firebase-admin');
exports.putTopic = (req, res) => {
const newTopic = {
@@ -9,7 +10,6 @@ exports.putTopic = (req, res) => {
admin.firestore().collection('topics').add(newTopic)
.then((doc) => {
const resTopic = newTopic;
newTopic.topicId = doc.id;
return res.status(200).json(resTopic);
})
.catch((err) => {
@@ -18,6 +18,8 @@ exports.putTopic = (req, res) => {
});
};
exports.getAllTopics = (req, res) => {
admin.firestore().collection('topics').get()
.then((data) => {
@@ -29,24 +31,6 @@ exports.getAllTopics = (req, res) => {
})
.catch((err) => {
console.error(err);
return res.status(500).json({error: 'Failed to fetch all topics.'})
return res.status(500).json({error: 'Failed to fetch all posts written by specific user.'})
})
};
exports.deleteTopic = (req, res) => {
const topic = db.doc(`/topics/${req.params.topicId}`);
topic.get().then((doc) => {
if (!doc.exists) {
return res.status(404).json({error: 'Topic not found'});
} else {
return topic.delete();
}
})
.then(() => {
res.json({ message: 'Topic successfully deleted!'});
})
.catch((err) => {
console.error(err);
return res.status(500).json({error: 'Failed to delete topic.'})
})
}
};

View File

@@ -1,3 +1,4 @@
/* eslint-disable prefer-arrow-callback */
/* eslint-disable promise/catch-or-return */
const { admin, db } = require("../util/admin");
@@ -7,6 +8,8 @@ const { validateUpdateProfileInfo } = require("../util/validator");
const firebase = require("firebase");
firebase.initializeApp(config);
var handle2Email = new Map();
exports.signup = (req, res) => {
const newUser = {
email: req.body.email,
@@ -75,9 +78,9 @@ exports.signup = (req, res) => {
email: newUser.email,
handle: newUser.handle,
createdAt: newUser.createdAt,
userId,
followedTopics: []
userId
};
handle2Email.set(userCred.handle, userCred.email);
return db.doc(`/users/${newUser.handle}`).set(userCred);
})
.then(() => {
@@ -95,6 +98,7 @@ exports.signup = (req, res) => {
exports.login = (req, res) => {
const user = {
email: req.body.email,
handle: req.body.handle,
password: req.body.password
};
@@ -103,63 +107,25 @@ exports.login = (req, res) => {
const emailRegEx = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
// Checks if email/username field is empty
// Email check
if (user.email.trim() === "") {
errors.email = "Email must not be blank.";
}
else if (!user.email.match(emailRegEx)) {
user.email = handle2Email.get(user.email);
}
// Checks if password field is empty
// Password check
if (user.password.trim() === "") {
errors.password = "Password must not be blank.";
}
// Checks if any of the above two errors were found
// Checking if any errors have been raised
if (Object.keys(errors).length > 0) {
return res.status(400).json(errors);
}
// Email/username field is username since it's not in email format
if (!user.email.match(emailRegEx)) {
var userDoc = db.collection("users").doc(`${user.email}`);
userDoc.get()
.then(function(doc) {
if (doc.exists) {
user.email = doc.data().email;
}
else {
return res.status(403).json({ general: "Invalid credentials. Please try again." });
}
return;
})
.then(function() {
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
return data.user.getIdToken();
})
.then((token) => {
return res.status(200).json({ token });
})
.catch((err) => {
console.error(err);
if (err.code === "auth/user-not-found" || err.code === "auth/invalid-email" || err.code === "auth/wrong-password") {
return res.status(403).json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).json({ error: err.code });
});
return;
})
.catch(function(err) {
if(!doc.exists) {
return res.status(403).json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).send(err);
});
}
// Email/username field is username
else {
firebase
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
@@ -170,65 +136,49 @@ exports.login = (req, res) => {
})
.catch((err) => {
console.error(err);
if (err.code === "auth/user-not-found" || err.code === "auth/invalid-email" || err.code === "auth/wrong-password") {
if (err.code === "auth/wrong-password" || err.code === "auth/invalid-email" || err.code === "auth/user-not-found") {
return res
.status(403)
.json({ general: "Invalid credentials. Please try again." });
.status(403)
.json({ general: "Invalid credentials. Please try again." });
}
return res.status(500).json({ error: err.code });
});
}
};
//Deletes user account
exports.deleteUser = (req, res) => {
var currentUser;
firebase.auth().onAuthStateChanged(function(user) {
currentUser = user;
if (currentUser) {
var post_query = db.collection("posts").where("userHandle", "==", req.user.handle);
post_query.get()
.then(function(myPosts) {
myPosts.forEach(function(doc) {
doc.ref.delete();
});
return;
})
/*db.collection("users").doc(`${currentUser.handle}`).delete()
.then(function() {
res.status(200).send("Successfully removed all user's posts from database.");
return;
})
.catch(function(err) {
res.status(500).send("Failed to remove all user's posts from database.", err);
});
db.collection("users").doc(`${req.user.handle}`).delete()
.then(function() {
res.status(200).send("Sucessfully removed user from database.");
res.status(200).send("Removed user from database.");
return;
})
.catch(function(err) {
res.status(500).send("Failed to remove user from database.", err);
});
});*/
//let ref = db.collection('users');
//let userDoc = ref.where('userId', '==', currentUser.uid).get();
//userDoc.ref.delete();
currentUser.delete()
.then(function() {
console.log("Successfully deleted user.");
res.status(200).send("Sucessfully deleted user.");
console.log("User successfully deleted.");
res.status(200).send("Deleted user.");
return;
})
.catch(function(err) {
console.log("Failed to delete user.", err);
console.log("Error deleting user.", err);
res.status(500).send("Failed to delete user.");
});
}
else {
console.log("Failed to deleter user or cannot get user.");
res.status(500).send("Failed to deleter user or cannot get user.");
console.log("Cannot get user.");
res.status(500).send("Cannot get user.");
}
});
};
@@ -249,6 +199,8 @@ exports.getProfileInfo = (req, res) => {
// Updates the data in the database of the user who is currently logged in
exports.updateProfileInfo = (req, res) => {
// TODO: Add functionality for adding/updating profile images
// Data validation
const { valid, errors, profileData } = validateUpdateProfileInfo(req);
if (!valid) return res.status(400).json(errors);

View File

@@ -29,7 +29,7 @@ app.post("/signup", signup);
app.post("/login", login);
//Deletes user account
app.delete("/delete", fbAuth, deleteUser);
app.delete("/delete", deleteUser);
app.get("/getUser", fbAuth, getUserDetails);
@@ -44,7 +44,7 @@ app.get("/user", fbAuth, getAuthenticatedUser);
/*------------------------------------------------------------------*
* handlers/post.js *
*------------------------------------------------------------------*/
const { getallPostsforUser, putPost
const { getallPostsforUser, putPost, getAllPosts
} = require("./handlers/post");
app.get("/getallPostsforUser", getallPostsforUser);
@@ -52,13 +52,13 @@ app.get("/getallPostsforUser", getallPostsforUser);
// Adds one post to the database
app.post("/putPost", fbAuth, putPost);
// Displays posts on home page
app.get("/getAllPosts", getAllPosts );
/*------------------------------------------------------------------*
* handlers/topic.js *
*------------------------------------------------------------------*/
const {
putTopic,
getAllTopics,
deleteTopic
const { putTopic, getAllTopics
} = require("./handlers/topic");
// add topic to database
@@ -67,7 +67,4 @@ app.post("/putTopic", fbAuth, putTopic);
// get all topics from database
app.get("/getAllTopics", fbAuth, getAllTopics);
// delete a specific topic
app.delete("/deleteTopic/:topicId", fbAuth, deleteTopic);
exports.api = functions.https.onRequest(app);

View File

@@ -535,11 +535,6 @@
"integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==",
"dev": true
},
"ansi-regex": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz",
"integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg=="
},
"ansi-styles": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
@@ -1195,18 +1190,11 @@
"progress": "^2.0.0",
"regexpp": "^2.0.1",
"semver": "^5.5.1",
"strip-ansi": "^4.0.0",
"strip-json-comments": "^2.0.1",
"table": "^5.2.3",
"text-table": "^0.2.0"
},
"dependencies": {
"ansi-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
"integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
"dev": true
},
"debug": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
@@ -1221,15 +1209,6 @@
"resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz",
"integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==",
"dev": true
},
"strip-ansi": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
"integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
"dev": true,
"requires": {
"ansi-regex": "^3.0.0"
}
}
}
},
@@ -2376,7 +2355,6 @@
"mute-stream": "0.0.7",
"run-async": "^2.2.0",
"rxjs": "^6.4.0",
"string-width": "^2.1.0",
"strip-ansi": "^5.1.0",
"through": "^2.3.6"
},
@@ -2425,12 +2403,6 @@
"integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=",
"optional": true
},
"is-fullwidth-code-point": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz",
"integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=",
"dev": true
},
"is-obj": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz",
@@ -3280,8 +3252,7 @@
"dev": true,
"requires": {
"ansi-styles": "^3.2.0",
"astral-regex": "^1.0.0",
"is-fullwidth-code-point": "^2.0.0"
"astral-regex": "^1.0.0"
}
},
"snakeize": {
@@ -3321,47 +3292,12 @@
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-0.1.2.tgz",
"integrity": "sha1-gIudDlb8Jz2Am6VzOOkpkZoanxo="
},
"string-width": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz",
"integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==",
"dev": true,
"requires": {
"is-fullwidth-code-point": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"dependencies": {
"ansi-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
"integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
"dev": true
},
"strip-ansi": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
"integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
"dev": true,
"requires": {
"ansi-regex": "^3.0.0"
}
}
}
},
"string_decoder": {
"version": "0.10.31",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
"integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=",
"optional": true
},
"strip-ansi": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz",
"integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==",
"requires": {
"ansi-regex": "^4.1.0"
}
},
"strip-json-comments": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
@@ -3408,7 +3344,6 @@
"dev": true,
"requires": {
"emoji-regex": "^7.0.1",
"is-fullwidth-code-point": "^2.0.0",
"strip-ansi": "^5.1.0"
}
},

View File

@@ -16,8 +16,7 @@
"axios": "^0.19.0",
"firebase": "^6.6.2",
"firebase-admin": "^8.6.0",
"firebase-functions": "^3.1.0",
"strip-ansi": "^5.2.0"
"firebase-functions": "^3.1.0"
},
"devDependencies": {
"eslint": "^5.12.0",

View File

@@ -52,3 +52,6 @@ body {
color: #1da1f2;
}
.a{
text-decoration: none;
}

View File

@@ -36,7 +36,6 @@ const theme = createMuiTheme(themeObject);
const token = localStorage.FBIdToken;
if (token) {
try {
const decodedToken = jwtDecode(token);
if (decodedToken.exp * 1000 < Date.now()) {
@@ -75,6 +74,7 @@ class App extends Component {
<Route exact path="/user" component={user} />
<Route exact path="/home" component={writeMicroblog} />
<Route exact path="/edit" component={editProfile} />
{/* <Route exact path="/user" component={userLine} /> */}
<AuthRoute exact path="/" component={home}/>
</Switch>

View File

@@ -5,7 +5,7 @@ import axios from 'axios';
class Writing_Microblogs extends Component {
constructor(props) {
super(props);
this.state = {
@@ -15,13 +15,13 @@ class Writing_Microblogs extends Component {
characterCount: 250
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeforPost = this.handleChangeforPost.bind(this);
this.handleChangeforTopics = this.handleChangeforTopics.bind(this);
}
handleChange(event) {
@@ -33,9 +33,10 @@ class Writing_Microblogs extends Component {
}
handleSubmit(event) {
// alert('A title for the microblog was inputted: ' + this.state.title + '\nA microblog was posted: ' + this.state.value);
const postData = {
body: this.state.value,
userHandle: "new user",
userImage: "bing-url",
microBlogTitle: this.state.title,
microBlogTopics: this.state.topics.split(', ')
@@ -45,7 +46,7 @@ class Writing_Microblogs extends Component {
}
axios
.post("/putPost", postData, headers)
.post('/putPost', postData, headers)
.then((res) =>{
alert('Post was shared successfully!')
console.log(res.data);
@@ -101,7 +102,7 @@ class Writing_Microblogs extends Component {
);
}
}
export default Writing_Microblogs;

View File

@@ -31,9 +31,13 @@ const styles = {
position: "absolute"
}
};
export class Navbar extends Component {
render() {
export class Navbar extends Component {
render() {
const authenticated = this.props.user.authenticated;
return (
<AppBar>
@@ -50,9 +54,11 @@ export class Navbar extends Component {
{authenticated && <Button component={ Link } to='/logout'>
Logout
</Button>}
{authenticated && <Button component={ Link } to='/delete'>
{/* Commented out the delete button, because it should probably go on
the profile or editProfile page instead of the NavBar */}
{/* <Button component={ Link } to='/delete'>
Delete Account
</Button>}
</Button> */}
</ToolBar>
</AppBar>
)

View File

@@ -0,0 +1,55 @@
import React, { Component } from 'react'
import withStyles from '@material-ui/core/styles/withStyles';
import Link from 'react-router-dom/Link';
// MUI Stuff
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import { Typography } from '@material-ui/core';
const styles = {
card:{
display: 'flex',
marginBottom: 20,
},
image:{
minWidth: 200,
},
content: {
padding: 25,
objectFit: 'cover',
}
}
class Posts extends Component {
render() {
const { classes, post : {body, createdAt, userImage, userHandle, commmentCount, likeCount, microBlogTopics} } = this.props
return (
<Card className={classes.card}>
<CardMedia
image={userImage}
title="Profile Image"
className={classes.image}/>
<CardContent class={classes.content}>
<Typography
variant = "h5"
component={Link}
to={`/users/${userHandle}`}
color="primary"
>
{userHandle}
</Typography>
<Typography
variant = "body2"
color="textSecondary">
{createdAt}
</Typography>
<Typography variant="body1">{body}</Typography>
</CardContent>
</Card>
)
}
}
export default withStyles(styles)(Posts);

View File

@@ -7,8 +7,7 @@ import Button from "@material-ui/core/Button";
import withStyles from "@material-ui/core/styles/withStyles";
// Redux stuff
//import { logoutUser } from "../redux/actions/userActions";
import { deleteUser } from "../redux/actions/userActions";
import { logoutUser } from "../redux/actions/userActions";
import { connect } from "react-redux";
const styles = {
@@ -33,8 +32,7 @@ const styles = {
export class Delete extends Component {
componentDidMount() {
//this.props.logoutUser();
this.props.deleteUser();
this.props.logoutUser();
this.props.history.push('/');
}
@@ -47,12 +45,10 @@ const mapStateToProps = (state) => ({
user: state.user
});
//const mapActionsToProps = { logoutUser };
const mapActionsToProps = { deleteUser };
const mapActionsToProps = { logoutUser };
Delete.propTypes = {
//logoutUser: PropTypes.func.isRequired,
deleteUser: PropTypes.func.isRequired,
logoutUser: PropTypes.func.isRequired,
user: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired
};

View File

@@ -16,15 +16,13 @@ import withStyles from "@material-ui/core/styles/withStyles";
// Redux stuff
import { connect } from 'react-redux';
import { loginUser } from '../redux/actions/userActions';
import { fontFamily } from '@material-ui/system';
//Theme
const styles = {
form: {
textAlign: "center"
},
textField: {
marginBottom: 20
marginBottom: 30
},
pageTitle: {
// marginTop: 20,
@@ -36,9 +34,6 @@ const styles = {
},
progress: {
position: "absolute"
},
p: {
fontFamily: "cursive",
}
};
@@ -109,12 +104,9 @@ export class Login extends Component {
<Grid item sm />
<Grid item sm>
<img src={logo} className="app-logo" alt="logo" />
<br></br>
<Typography variant="p" className={classes.pageTitle} fontFamily = "Georgia, serif">
<b>Log in to Twistter</b>
<br></br>
<Typography variant="h2" className={classes.pageTitle}>
Log in to Twistter
</Typography>
<br></br>
<form noValidate onSubmit={this.handleSubmit}>
<TextField
id="email"

View File

@@ -16,17 +16,13 @@ import withStyles from "@material-ui/core/styles/withStyles";
// Redux stuff
import { connect } from 'react-redux';
import { signupUser } from '../redux/actions/userActions';
import { border } from '@material-ui/system';
const styles = {
form: {
textAlign: "center"
},
textField: {
marginBottom: 20,
//border: "1px solid #234",
display: "inline-block",
boxSizing: "border-box",
marginBottom: 30
},
pageTitle: {
marginBottom: 40
@@ -37,14 +33,6 @@ const styles = {
},
progress: {
position: "absolute"
},
div: {
borderRadius: "5px",
backgroundColor: "grey",
padding: "20px",
},
p: {
fontFamily: "Segoe UI",
}
};
@@ -104,12 +92,9 @@ export class Signup extends Component {
<Grid item sm />
<Grid item sm>
<img src={logo} className="app-logo" alt="logo" />
<br></br>
<Typography variant="p" className={classes.pageTitle}>
<b>Create a new account</b>
<br></br>
<Typography variant="h2" className={classes.pageTitle}>
Create a new account
</Typography>
<br></br>
<form noValidate onSubmit={this.handleSubmit}>
<TextField
id="handle"
@@ -161,8 +146,6 @@ export class Signup extends Component {
onChange={this.handleChange}
fullWidth
/>
<br></br>
<br></br>
<Button
type="submit"
variant="contained"

View File

@@ -6,68 +6,78 @@ import axios from 'axios';
import { makeStyles, styled } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Card from '@material-ui/core/Card';
import CardMedia from '@material-ui/core/CardMedia';
import CardContent from '@material-ui/core/CardContent';
import Chip from '@material-ui/core/Chip';
import Paper from '@material-ui/core/Paper';
import Typography from "@material-ui/core/Typography";
import AddCircle from '@material-ui/icons/AddCircle';
import TextField from '@material-ui/core/TextField';
// component
import Profile from '../components/profile/Profile';
import Userline from '../Userline';
import noImage from '../images/no-img.png';
import Posts from '../components/post/Posts';
const PostCard = styled(Card)({
background: 'linear-gradient(45deg, #1da1f2 90%)',
border: 3,
borderRadius: 3,
height:325,
width: 345,
padding: '0 30px',
});
const MyChip = styled(Chip)({
margin: 2,
color: 'primary'
});
const styles = (theme) => ({
...theme
});
const handleDelete = () => {
alert("Delete this topic!");
}
const handleAddCircle = () => {
alert("Add topic");
}
class user extends Component {
state = {
profile: null,
imageUrl: null,
topics: null,
newTopic: null
topics: null
};
handleDelete = (topic) => {
alert(`Delete topic: ${topic}!`);
}
handleAddCircle = () => {
axios.post('/putTopic', {
topic: this.state.newTopic
})
.then(function () {
location.reload();
})
.catch(function (err) {
console.log(err);
});
}
handleChange(event) {
this.setState({
newTopic: event.target.value
})
}
componentDidMount() {
axios
.get("/user")
.then(res => {
console.log(res.data.credentials.handle);
this.setState({
profile: res.data.credentials.handle,
imageUrl: res.data.credentials.imageUrl
profile: res.data.credentials.handle
});
})
.catch(err => console.log(err));
axios
.get("/getAllTopics")
.then(res => {
console.log(res.data[1]);
this.setState({
topics: res.data
})
})
.catch(err => console.log(err));
axios.get('/getAllPosts')
.then(res => {
this.setState({
posts: res.data
})
})
.catch(err => console.log(err));
}
render() {
const classes = this.props;
@@ -80,40 +90,27 @@ class user extends Component {
let topicsMarkup = this.state.topics ? (
this.state.topics.map(topic => <MyChip
label={{topic}.topic.topic}
key={{topic}.topic.topicId}
onDelete={ (topic) => this.handleDelete(topic)}/>)
onDelete={handleDelete}/>)
) : (<p> loading topics...</p>);
let imageMarkup = this.state.imageUrl ? (
<img
src={this.state.imageUrl}
height="250"
width="250"
/>
) : (<img src={noImage}/>);
let posts = classes.data
let recentPostsMarkup = posts ? (
this.state.posts.map(post => <Posts key={post.postId} post={post}/>)
) : ( <p> Loading... </p> );
return (
<Grid container spacing={16}>
<Grid item sm={8} xs={12}>
<p>Post</p>
{recentPostsMarkup}
</Grid>
<Grid item sm={4} xs={12}>
{imageMarkup}
<img src={noImage}/>
{profileMarkup}
{topicsMarkup}
<TextField
id="newTopic"
label="new topic"
defaultValue=""
margin="normal"
variant="outlined"
value={this.state.newTopic}
onChange={ (event) => this.handleChange(event)}
/>
<AddCircle
color="primary"
<MyChip
icon={<AddCircle />}
clickable
onClick={this.handleAddCircle}
onClick={handleAddCircle}
/>
</Grid>
</Grid>
@@ -121,4 +118,12 @@ class user extends Component {
}
}
Userline.PropTypes = {
handle: PropTypes.object.isRequired
};
const mapStateToProps = (state) => ({
user: state.user
});
export default user;