-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
99 lines (84 loc) · 2.67 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//App.js
import React, { useState, useEffect } from "react";
import {
HashRouter,
Switch,
Route
} from "react-router-dom";
import { withAuthenticator } from '@aws-amplify/ui-react';
import { css } from '@emotion/css';
import { API, Storage, Auth } from 'aws-amplify';
import '@aws-amplify/ui-react/styles.css';
import { listPosts } from './graphql/queries';
import Posts from './Posts';
import Post from './Post';
import Header from './Header';
import CreatePost from './CreatePost';
import Button from './Button';
function Router({user, signOut}) {
/* create a couple of pieces of initial state */
const [showOverlay, updateOverlayVisibility] = useState(false);
const [posts, updatePosts] = useState([]);
const [myPosts, updateMyPosts] = useState([]);
/* fetch posts when component loads */
useEffect(() => {
fetchPosts();
}, []);
async function fetchPosts() {
/* query the API, ask for 100 items */
let postData = await API.graphql({ query: listPosts, variables: { limit: 100 }});
let postsArray = postData.data.listPosts.items;
/* map over the image keys in the posts array, get signed image URLs for each image */
postsArray = await Promise.all(postsArray.map(async post => {
const imageKey = await Storage.get(post.image);
post.image = imageKey;
return post;
}));
/* update the posts array in the local state */
setPostState(postsArray);
}
async function setPostState(postsArray) {
const user = await Auth.currentAuthenticatedUser();
const myPostData = postsArray.filter((p) => p.owner === user.username);
updateMyPosts(myPostData);
updatePosts(postsArray);
}
return (
<>
<HashRouter>
<div className={contentStyle}>
<Header />
<hr className={dividerStyle} />
<Button title="New Post" onClick={() => updateOverlayVisibility(true)} />
<Switch>
<Route exact path="/" >
<Posts posts={posts} />
</Route>
<Route exact path="/myposts">
<Posts posts={myPosts} />
</Route>
<Route path="/post/:id" >
<Post />
</Route>
</Switch>
</div>
<button onClick={signOut}>Sign out</button>
</HashRouter>
{ showOverlay && (
<CreatePost
updateOverlayVisibility={updateOverlayVisibility}
updatePosts={setPostState}
posts={posts}
/>
)}
</>
);
}
const dividerStyle = css`
margin-top: 15px;
`
const contentStyle = css`
min-height: calc(100vh - 45px);
padding: 0px 40px;
`
export default withAuthenticator(Router);