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
100
101
102
103
104
|
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import {
createMuiTheme,
ThemeProvider,
makeStyles
} from '@material-ui/core/styles';
import { CssBaseline } from '@material-ui/core';
import teal from '@material-ui/core/colors/teal';
import 'typeface-roboto';
import Header from './components/Header/Header';
import ProfilePage from './pages/ProfilePage/ProfilePage';
import FeedPage from './pages/FeedPage/FeedPage';
import AuthPage from './pages/AuthPage/AuthPage';
import { User, Page } from './types';
import { get, post } from './requests';
import ScrollTopArrow from './components/ScrollTopArrow/ScrollTopArrow';
const theme = createMuiTheme({
palette: {
primary: {
main: teal[700]
}
}
});
const useStyles = makeStyles({
root: {
width: theme.spacing(75),
marginTop: theme.spacing(15),
margin: '0 auto'
}
});
const App: React.FC = () => {
const [user, setUser] = React.useState<User | undefined>();
const [page, setPage] = useState<Page>({ prefix: 'feed', id: '' });
const classes = useStyles();
const navigate = (prefix: string, id?: string): void => {
if (prefix === 'profile' && !id && !user) {
setPage({
prefix: 'auth',
id: ''
});
} else {
setPage({
prefix,
id: (id || user?._id || '')
});
}
};
const logIn = (name: string, password: string): Promise<boolean> => {
return post('/authentication', {
strategy: 'local',
name,
password
}).then(response => {
const me = response.data.user;
const token = response.data.accessToken;
setUser(me);
localStorage.setItem('userId', me._id);
localStorage.setItem('token', token);
navigate('profile', me._id);
return true;
}).catch(() => false);
};
const logOut = () => {
setUser(undefined);
localStorage.removeItem('userId');
localStorage.removeItem('token');
navigate('auth');
};
useEffect(() => {
const userId = localStorage.getItem('userId');
if (userId) {
get(`/users/${userId}`).then(response => {
setUser(response.data);
});
}
}, []);
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<Header navigate={navigate} />
<div className={classes.root}>
{ page.prefix === 'profile' && <ProfilePage logOut={logOut} id={page.id} navigate={navigate} /> }
{ page.prefix === 'feed' && <FeedPage navigate={navigate} /> }
{ page.prefix === 'auth' && <AuthPage logIn={logIn} /> }
</div>
<ScrollTopArrow />
</ThemeProvider>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
|