├── .env
├── .eslintrc.js
├── .gitignore
├── README.md
├── jsconfig.json
├── package-lock.json
├── package.json
├── preview.png
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── components
├── GuardRoute.js
├── Layout
│ ├── index.css
│ └── index.js
├── LeftMenu.js
├── RightMenu.js
└── SwitchRoute.js
├── hooks
├── use-auth.js
└── use-post.js
├── index.css
├── index.js
├── logo.svg
├── pages
├── About.js
├── Account.js
├── ForgotPassword.js
├── Home.js
├── Login.js
├── NotAuthorized.js
├── NotFound.js
├── Post.js
├── Posts.js
└── Signup.js
├── routes.js
├── serviceWorker.js
├── setupTests.js
├── store
├── general.js
├── index.js
├── other.js
├── reducers.js
└── states.js
└── utils
└── storage.js
/.env:
--------------------------------------------------------------------------------
1 | REACT_APP_API_URL=http://localhost:4000
2 | REACT_APP_STORAGE_PREFIX = 'RSA-'
3 | PORT=3000
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | env: {
3 | browser: true,
4 | es6: true,
5 | jest: true
6 | },
7 | extends: [
8 | 'eslint:recommended',
9 | 'plugin:react/recommended',
10 | 'standard',
11 | // 'standard-jsx'
12 | ],
13 | globals: {
14 | Atomics: 'readonly',
15 | SharedArrayBuffer: 'readonly'
16 | },
17 | parser: 'babel-eslint',
18 | parserOptions: {
19 | ecmaFeatures: {
20 | jsx: true
21 | },
22 | ecmaVersion: 2018,
23 | sourceType: 'module',
24 | },
25 | plugins: [
26 | 'react'
27 | ],
28 | rules: {
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development
18 | .env.development.local
19 | .env.test.local
20 | .env.production.local
21 |
22 | npm-debug.log*
23 | yarn-debug.log*
24 | yarn-error.log*
25 |
26 | .now
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React Smart App
2 |
3 | Boilerplate React App
4 |
5 | This project was bootstrapped with
6 | - [Create React App](https://github.com/facebook/create-react-app);
7 | - [Ant Design](https://ant.design)
8 | - [React Router](https://ant.design)
9 | - State Management with Persisted - React Hooks (Redux Like)
10 | - Some Sample Page & User Interface
11 |
12 | 
13 |
14 | [demo](https://react-smart-app.now.sh)
15 |
16 | ## Installation
17 |
18 | - clone this repo
19 | - npm install
20 | - npm run start
21 | - enjoy
22 |
23 | ## Available Scripts
24 |
25 | In the project directory, you can run:
26 |
27 | ### `npm start`
28 |
29 | Runs the app in the development mode.
30 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
31 |
32 | The page will reload if you make edits.
33 | You will also see any lint errors in the console.
34 |
35 | ### `npm test`
36 |
37 | Launches the test runner in the interactive watch mode.
38 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
39 |
40 | ### `npm run build`
41 |
42 | Builds the app for production to the `build` folder.
43 | It correctly bundles React in production mode and optimizes the build for the best performance.
44 |
45 | The build is minified and the filenames include the hashes.
46 | Your app is ready to be deployed!
47 |
48 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
49 |
50 | ### `npm run eject`
51 |
52 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
53 |
54 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
55 |
56 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
57 |
58 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
59 |
60 | ## Learn More
61 |
62 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
63 |
64 | To learn React, check out the [React documentation](https://reactjs.org/).
65 |
66 | ### Code Splitting
67 |
68 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
69 |
70 | ### Analyzing the Bundle Size
71 |
72 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
73 |
74 | ### Making a Progressive Web App
75 |
76 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
77 |
78 | ### Advanced Configuration
79 |
80 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
81 |
82 | ### Deployment
83 |
84 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
85 |
86 | ### `npm run build` fails to minify
87 |
88 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
89 |
--------------------------------------------------------------------------------
/jsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": "src"
4 | },
5 | "include": ["src"]
6 | }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "exam-template",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@ant-design/icons": "^4.0.6",
7 | "@testing-library/jest-dom": "^4.2.4",
8 | "@testing-library/react": "^9.5.0",
9 | "@testing-library/user-event": "^7.2.1",
10 | "antd": "^4.1.4",
11 | "axios": "^0.19.2",
12 | "immer": "^6.0.3",
13 | "lz-string": "^1.4.4",
14 | "react": "^16.13.1",
15 | "react-dom": "^16.13.1",
16 | "react-router-dom": "^5.1.2",
17 | "react-scripts": "3.4.1",
18 | "timeago-react": "^3.0.0",
19 | "use-immer": "^0.4.0"
20 | },
21 | "scripts": {
22 | "start": "react-scripts start",
23 | "build": "react-scripts build",
24 | "test": "react-scripts test",
25 | "eject": "react-scripts eject"
26 | },
27 | "eslintConfig": {
28 | "extends": "react-app"
29 | },
30 | "browserslist": {
31 | "production": [
32 | ">0.2%",
33 | "not dead",
34 | "not op_mini all"
35 | ],
36 | "development": [
37 | "last 1 chrome version",
38 | "last 1 firefox version",
39 | "last 1 safari version"
40 | ]
41 | },
42 | "devDependencies": {
43 | "babel-eslint": "^10.1.0",
44 | "eslint": "^6.8.0",
45 | "eslint-config-standard": "^14.1.1",
46 | "eslint-config-standard-jsx": "^8.1.0",
47 | "eslint-plugin-import": "^2.20.2",
48 | "eslint-plugin-node": "^11.1.0",
49 | "eslint-plugin-promise": "^4.2.1",
50 | "eslint-plugin-react": "^7.19.0",
51 | "eslint-plugin-standard": "^4.0.1",
52 | "standard-engine": "^12.0.0"
53 | },
54 | "babel": {
55 | "plugins": [
56 | "transform-remove-console"
57 | ]
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/preview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hscstudio/react-smart-app/24ac36d8e5587f036ce1e8ca621ca25ee62f4fe7/preview.png
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hscstudio/react-smart-app/24ac36d8e5587f036ce1e8ca621ca25ee62f4fe7/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React Smart App
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hscstudio/react-smart-app/24ac36d8e5587f036ce1e8ca621ca25ee62f4fe7/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hscstudio/react-smart-app/24ac36d8e5587f036ce1e8ca621ca25ee62f4fe7/public/logo512.png
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "Smart App",
3 | "name": "React Smart App",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .post-image{
2 | margin-right: 5px;
3 | margin-top: -10px;
4 | }
5 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Suspense } from 'react'
2 | import { BrowserRouter as Router } from 'react-router-dom'
3 | import SwitchRoute from 'components/SwitchRoute'
4 | import routes from 'routes'
5 | import { Spin } from 'antd'
6 |
7 | import 'App.css'
8 |
9 | function App () {
10 | return (
11 |
15 | }>
16 |
17 |
18 |
19 |
20 | )
21 | }
22 |
23 | export default App
24 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { render } from '@testing-library/react'
3 | import App from './App'
4 |
5 | test('renders learn react link', () => {
6 | const { getByText } = render()
7 | const linkElement = getByText(/learn react/i)
8 | expect(linkElement).toBeInTheDocument()
9 | })
10 |
--------------------------------------------------------------------------------
/src/components/GuardRoute.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import {
3 | Route,
4 | Redirect
5 | } from 'react-router-dom'
6 | import { useShared } from 'store'
7 | import PropTypes from 'prop-types'
8 |
9 | const GuardRoute = ({ auth, children, ...rest }) => {
10 | const general = useShared('general')[0]
11 | const safeProps = { ...rest }
12 | delete safeProps.component
13 | return (
14 | (auth && general.guest)
15 | ?
16 | : {
19 | return children
20 | }}
21 | />
22 | )
23 | }
24 |
25 | GuardRoute.propTypes = {
26 | auth: PropTypes.bool,
27 | children: PropTypes.node.isRequired
28 | }
29 |
30 | export default GuardRoute
31 |
--------------------------------------------------------------------------------
/src/components/Layout/index.css:
--------------------------------------------------------------------------------
1 | .BaseLayout .ant-layout-header {
2 | padding: 0 15px;
3 | background-color: #0288d1;
4 | color: #f1f8e9;
5 | position: -webkit-sticky;
6 | position: sticky;
7 | top: -1px;
8 | z-index: 2;
9 | }
10 |
11 | .BaseLayout .ant-layout-header h2{
12 | text-align: center;
13 | color: #fff;
14 | margin: 0;
15 | line-height: 64px;
16 | cursor: pointer;
17 | }
18 |
19 | .BaseLayout .ant-layout-header button.toolbar-btn{
20 | height: 64px;
21 | }
22 |
23 | .BaseLayout .ant-layout-header button.toolbar-btn > span{
24 | font-size: 1.5em;
25 | color: #fff;
26 | }
27 |
28 | .BaseLayout .ant-layout-header button{
29 | color: #fff;
30 | }
31 |
32 | .BaseLayout .content {
33 | background-color: #eee;
34 | position: relative;
35 | padding: 10px;
36 | }
37 |
38 | .BaseLayout .content .page{
39 | background-color: #fff;
40 | padding: 10px;
41 | min-height: calc(100vh - 65px);
42 | min-height: -o-calc(100% - 65px); /* opera */
43 | min-height: -webkit-calc(100% - 65px); /* google, safari */
44 | min-height: -moz-calc(100% - 65px); /* firefox */
45 | }
46 |
47 | .BaseLayout .ant-layout-footer{
48 | padding: 15px;
49 | height: 48px;
50 | background-color: #fff;
51 | border-top: 1px solid #0288d1;
52 | width: 100%;
53 | text-align: center;
54 | }
55 |
56 | .ant-drawer-body{
57 | padding: 0;
58 | }
--------------------------------------------------------------------------------
/src/components/Layout/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import PropTypes from 'prop-types'
3 | import { Layout as BaseLayout, Row, Col, Button, Drawer, Menu, Dropdown, message as Message } from 'antd'
4 | import {
5 | MenuFoldOutlined,
6 | LeftOutlined,
7 | SettingOutlined,
8 | LogoutOutlined,
9 | LoginOutlined,
10 | UserOutlined
11 | } from '@ant-design/icons'
12 | import { Link, useHistory } from 'react-router-dom'
13 | import { useShared } from 'store'
14 | import useAuth from 'hooks/use-auth'
15 | import LeftMenu from 'components/LeftMenu'
16 | import RightMenu from 'components/RightMenu'
17 | import './index.css'
18 |
19 | const { Header, Content, Footer } = BaseLayout
20 |
21 | function getPage () {
22 | let currentPage = 'home'
23 | if (window.location.pathname.includes('/about')) currentPage = 'about'
24 | return currentPage
25 | }
26 |
27 | function getPrevUrl (currentPage) {
28 | return (currentPage !== 'home') ? '/home' : ''
29 | }
30 |
31 | function Layout ({ children, title, link }) {
32 | const useGeneral = useShared('general')
33 | const general = useGeneral[0]
34 | const { user, isGuest, logout } = useAuth()
35 | const history = useHistory()
36 |
37 | const authMenu = (
38 |
46 | )
47 |
48 | const currentPage = getPage()
49 | const mainPages = ['home']
50 | const prevUrl = getPrevUrl(currentPage)
51 | const [drawer, setDrawer] = React.useState({ visible: false })
52 |
53 | return (
54 |
55 |
56 |
57 |
58 | {(mainPages.includes(currentPage))
59 | ? } onClick={() => {
60 | setDrawer({
61 | title: 'Main Menu',
62 | placement: 'left',
63 | visible: true
64 | })
65 | }} />
66 | : (prevUrl !== '')
67 | ? } onClick={() => history.push(prevUrl)} />
68 | : (general.prevUrl !== '')
69 | ? } onClick={() => history.push(general.prevUrl)} />
70 | : } onClick={() => history.push('/home')} />
71 | }
72 |
73 |
74 | history.push('/home')} >{title}
75 |
76 |
77 | {(currentPage === 'about') &&
78 | } onClick={() => {
79 | setDrawer({
80 | title: 'Right Menu',
81 | placement: 'right',
82 | visible: true
83 | })
84 | }} />}
85 | {isGuest !== true
86 | ?
89 |
92 |
93 | : } onClick={() => {
94 | history.push('/login')
95 | }} />
96 | }
97 |
98 |
99 |
100 |
101 |
102 | {children}
103 |
104 |
105 |
108 |
109 | {
114 | setDrawer({
115 | title: drawer.title,
116 | placement: drawer.placement,
117 | visible: false
118 | })
119 | }}
120 | visible={drawer.visible}
121 | >
122 | {(currentPage === 'about')
123 | ?
124 | :
125 | }
126 |
127 |
128 | )
129 | }
130 |
131 | Layout.defaultProps = {
132 | title: 'React Smart App',
133 | link: '/home',
134 | children: <>...>
135 | }
136 |
137 | Layout.propTypes = {
138 | children: PropTypes.node,
139 | title: PropTypes.string,
140 | link: PropTypes.string
141 | }
142 |
143 | export default Layout
144 |
--------------------------------------------------------------------------------
/src/components/LeftMenu.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | // import { useShared } from 'store'
3 | import { Divider, Menu } from 'antd'
4 | import { Link } from 'react-router-dom'
5 | import {
6 | HomeOutlined,
7 | UserOutlined,
8 | InfoCircleOutlined,
9 | LoginOutlined,
10 | UserAddOutlined,
11 | UnorderedListOutlined
12 | } from '@ant-design/icons'
13 | import useAuth from 'hooks/use-auth'
14 |
15 | // const { SubMenu } = Menu
16 |
17 | function LeftMenu () {
18 | const { isGuest } = useAuth()
19 | const menus = [
20 | { path: '/home', icon: , title: 'Home' },
21 | { path: '/login', icon: , title: 'Login', auth: false },
22 | { path: '/signup', icon: , title: 'Signup', auth: false },
23 | { path: '/posts', icon: , title: 'Post', auth: true },
24 | { path: '/account', icon: , title: 'Account', auth: true },
25 | { path: '/about', icon: , title: 'About' }
26 | ]
27 | return
28 | {/*
*/}
52 |
53 |
73 |
74 |
75 | }
76 |
77 | export default LeftMenu
78 |
--------------------------------------------------------------------------------
/src/components/RightMenu.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | // import { useShared } from 'store'
3 | import { Divider } from 'antd'
4 | function RightMenu () {
5 | return
8 | }
9 |
10 | export default RightMenu
11 |
--------------------------------------------------------------------------------
/src/components/SwitchRoute.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import PropTypes from 'prop-types'
3 | import {
4 | Switch, Redirect
5 | } from 'react-router-dom'
6 | import GuardRoute from 'components/GuardRoute'
7 |
8 | const SwitchRoute = ({ routes = [] }) => {
9 | return (
10 |
11 | {routes.map((route, i) => {
12 | const { component: Component, ...rest } = route
13 | return
14 | })}
15 |
16 |
17 | )
18 | }
19 |
20 | SwitchRoute.propTypes = {
21 | routes: PropTypes.array
22 | }
23 |
24 | export default SwitchRoute
25 |
--------------------------------------------------------------------------------
/src/hooks/use-auth.js:
--------------------------------------------------------------------------------
1 | // import React from 'react'
2 | import Axios from 'axios'
3 | import { useShared } from 'store'
4 |
5 | const API_URL = process.env.REACT_APP_API_URL
6 |
7 | Axios.defaults.validateStatus = function () {
8 | return true
9 | }
10 |
11 | export default () => {
12 | const [general, setGeneral] = useShared('general')
13 | const user = general.user
14 | const isGuest = general.guest
15 |
16 | const signup = async (props) => {
17 | const { username, email, password } = props
18 | const payload = new FormData()
19 | payload.append('username', username)
20 | payload.append('email', email)
21 | payload.append('password', password)
22 | try {
23 | const response = await Axios.post(`${API_URL}/api/v1/signup`, payload)
24 | const { status, data, message } = response.data
25 | console.log(response.data)
26 | if (status === 'success') {
27 | setGeneral({
28 | type: 'SET',
29 | payload: {
30 | state: 'user',
31 | data
32 | }
33 | })
34 | setGeneral({
35 | type: 'SET',
36 | payload: {
37 | state: 'guest',
38 | data: false
39 | }
40 | })
41 | return { status, message: 'Signup successfully' }
42 | } else {
43 | return { status, message }
44 | }
45 | } catch (e) {
46 | return { status: 'error', message: 'Fatal error' }
47 | }
48 | }
49 |
50 | const login = async (props) => {
51 | const { username, password } = props
52 | const payload = new FormData()
53 | payload.append('username', username)
54 | payload.append('password', password)
55 | try {
56 | const response = await Axios.post(`${API_URL}/api/v1/login`, payload)
57 | const { status, data, message } = response.data
58 | if (status === 'success') {
59 | setGeneral({
60 | type: 'SET',
61 | payload: {
62 | state: 'user',
63 | data
64 | }
65 | })
66 | setGeneral({
67 | type: 'SET',
68 | payload: {
69 | state: 'guest',
70 | data: false
71 | }
72 | })
73 | return { status, message: 'Login successfully' }
74 | } else {
75 | return { status, message }
76 | }
77 | } catch (e) {
78 | return { status: 'error', message: 'Fatal error' }
79 | }
80 | }
81 |
82 | const logout = () => {
83 | setGeneral({
84 | type: 'SET',
85 | payload: {
86 | state: 'user',
87 | data: {}
88 | }
89 | })
90 | setGeneral({
91 | type: 'SET',
92 | payload: {
93 | state: 'guest',
94 | data: true
95 | }
96 | })
97 | return { status: 'success', message: 'Logout successfully' }
98 | }
99 |
100 | const updateProfile = async (props) => {
101 | const options = {
102 | headers: {
103 | 'Content-Type': 'multipart/form-data',
104 | Authorization: `Bearer ${user.token}`
105 | },
106 | timeout: 30000
107 | }
108 | const { username, email } = props
109 | const payload = new FormData()
110 | payload.append('username', username)
111 | payload.append('email', email)
112 | try {
113 | const response = await Axios.post(`${API_URL}/api/v1/profile`, payload, options)
114 | const { status, data, message } = response.data
115 | if (status === 'success') {
116 | const concatData = { ...user, ...data }
117 | setGeneral({
118 | type: 'SET',
119 | payload: {
120 | state: 'user',
121 | data: concatData
122 | }
123 | })
124 | return { status, message: 'Update successfully' }
125 | } else {
126 | return { status, message }
127 | }
128 | } catch (e) {
129 | console.log(e)
130 | return { status: 'error', message: 'Fatal error x' }
131 | }
132 | }
133 |
134 | return {
135 | user, isGuest, signup, login, logout, updateProfile
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/src/hooks/use-post.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Axios from 'axios'
3 | import useAuth from 'hooks/use-auth'
4 |
5 | const API_URL = process.env.REACT_APP_API_URL
6 |
7 | Axios.defaults.validateStatus = function () {
8 | return true
9 | }
10 |
11 | const POST_PER_PAGE = 10
12 |
13 | const getPosts = async (props, callback) => {
14 | const { user, page } = props
15 | const options = {
16 | headers: {
17 | 'Content-Type': 'multipart/form-data',
18 | Authorization: `Bearer ${user.token}`
19 | },
20 | timeout: 30000
21 | }
22 | try {
23 | const response = await Axios.get(`${API_URL}/api/v1/posts?page=${page}`, options)
24 | callback(response.data)
25 | } catch (e) {
26 | const data = {
27 | status: 'error',
28 | message: 'Fatal error'
29 | }
30 | callback(data)
31 | }
32 | }
33 |
34 | export default () => {
35 | const { user } = useAuth()
36 | const [posts, setPosts] = React.useState([])
37 | const [loadingPosts, setLoadingPosts] = React.useState([])
38 | const [initial, setInitial] = React.useState(true)
39 | const [loading, setLoading] = React.useState(false)
40 | const [page, setPage] = React.useState(1)
41 | const [visibleLoadMore, setVisibleLoadMore] = React.useState(true)
42 | const [error, setError] = React.useState('')
43 | const onLoadMore = () => {
44 | setLoading(true)
45 | setLoadingPosts(
46 | loadingPosts.concat([
47 | ...new Array(POST_PER_PAGE)].map(() => ({
48 | loading: true, name: {}
49 | })))
50 | )
51 |
52 | getPosts({ user, page }, response => {
53 | const { status, data, message } = response
54 | if (status === 'success') {
55 | if (data.data && data.data.length > 0) {
56 | const concatData = [...posts, ...data.data]
57 | setLoadingPosts(concatData)
58 | setPosts(concatData)
59 | if (page === data.lastPage) {
60 | setVisibleLoadMore(false)
61 | } else {
62 | setVisibleLoadMore(true)
63 | setPage(page + 1)
64 | }
65 | } else {
66 | setLoadingPosts(posts)
67 | setVisibleLoadMore(false)
68 | }
69 | } else {
70 | setError(message)
71 | }
72 | })
73 |
74 | setLoading(false)
75 | }
76 |
77 | React.useEffect(() => {
78 | if (initial && user) {
79 | setLoading(true)
80 | setInitial(false)
81 | getPosts({ user, page }, response => {
82 | const { status, data, message } = response
83 | if (status === 'success') {
84 | if (data.data && data.data.length > 0) {
85 | setPosts(data.data)
86 | setLoadingPosts(data.data)
87 | }
88 | if (page === data.lastPage) {
89 | setVisibleLoadMore(false)
90 | } else {
91 | setVisibleLoadMore(true)
92 | setPage(page + 1)
93 | }
94 | } else {
95 | setError(message)
96 | }
97 | })
98 | setLoading(false)
99 | }
100 | }, [initial, page, user])
101 |
102 | return {
103 | user,
104 | getPosts,
105 | initial,
106 | setInitial,
107 | posts,
108 | setPosts,
109 | loadingPosts,
110 | setLoadingPosts,
111 | loading,
112 | setLoading,
113 | page,
114 | setPage,
115 | visibleLoadMore,
116 | setVisibleLoadMore,
117 | onLoadMore,
118 | error
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom'
3 | import 'antd/dist/antd.min.css'
4 | // import 'antd/dist/antd.dark.min.css'
5 | import App from './App'
6 | import * as serviceWorker from './serviceWorker'
7 | import { SharedProvider } from './store'
8 |
9 | if (process.env.NODE_ENV === 'production') {
10 | console.log = () => {}
11 | }
12 |
13 | ReactDOM.render(
14 | <>
15 |
16 |
17 |
18 | >,
19 | document.getElementById('root')
20 | )
21 |
22 | // If you want your app to work offline and load faster, you can change
23 | // unregister() to register() below. Note this comes with some pitfalls.
24 | // Learn more about service workers: https://bit.ly/CRA-PWA
25 | serviceWorker.unregister()
26 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/src/pages/About.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Layout from 'components/Layout'
3 |
4 | const About = () => {
5 | return <>
6 |
7 |
8 |
Halaman About
9 |
10 |
11 | >
12 | }
13 |
14 | export default About
15 |
--------------------------------------------------------------------------------
/src/pages/Account.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Layout from 'components/Layout'
3 | import useAuth from 'hooks/use-auth'
4 | import { Form, Input, Button, message as Message } from 'antd'
5 | import { UserOutlined, MailOutlined } from '@ant-design/icons'
6 |
7 | const Account = () => {
8 | const { user, updateProfile } = useAuth()
9 | const onFinish = async values => {
10 | const { username, email } = values
11 | const { status, message } = await updateProfile({ username, email })
12 | if (status === 'success') {
13 | Message.success(message)
14 | } else {
15 | Message.error(message)
16 | }
17 | }
18 | return <>
19 |
20 |
21 |
Halaman Account
22 |
40 | } placeholder="Username" />
41 |
42 |
51 | } placeholder="Email" />
52 |
53 |
54 |
55 |
58 |
59 |
60 |
61 |
62 | >
63 | }
64 |
65 | export default Account
66 |
--------------------------------------------------------------------------------
/src/pages/ForgotPassword.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Layout from 'components/Layout'
3 |
4 | const ForgotPassword = () => {
5 | return <>
6 |
7 |
8 |
Forgot Password
9 | Feature not yet! :)
10 |
11 |
12 | >
13 | }
14 |
15 | export default ForgotPassword
16 |
--------------------------------------------------------------------------------
/src/pages/Home.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Layout from 'components/Layout'
3 |
4 | const Home = () => {
5 | return <>
6 |
7 |
8 |
Halaman Home
9 | source: https://github.com/hscstudio/react-smart-app
10 |
11 |
12 | >
13 | }
14 |
15 | export default Home
16 |
--------------------------------------------------------------------------------
/src/pages/Login.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Layout from 'components/Layout'
3 | import { Form, Input, Button, Checkbox, message as Message } from 'antd'
4 | import { UserOutlined, LockOutlined } from '@ant-design/icons'
5 | import { useHistory } from 'react-router-dom'
6 | import useAuth from 'hooks/use-auth'
7 |
8 | const Login = () => {
9 | const { login } = useAuth()
10 | const history = useHistory()
11 |
12 | const onFinish = async values => {
13 | const { username, password } = values
14 | const { status, message } = await login({ username, password })
15 | if (status === 'success') {
16 | Message.success(message)
17 | history.push('/home')
18 | } else {
19 | Message.error(message)
20 | }
21 | }
22 | return <>
23 |
24 |
25 |
Form Login
26 | * username: admin & password: 123456
27 |
44 | } placeholder="Username" />
45 |
46 |
55 | }
57 | type="password"
58 | placeholder="Password"
59 | />
60 |
61 |
62 |
63 | Remember me
64 |
65 |
66 |
67 | Forgot password
68 |
69 |
70 |
71 |
72 |
75 | or
76 | Signup now!
77 |
78 |
79 |
80 |
81 | >
82 | }
83 |
84 | export default Login
85 |
--------------------------------------------------------------------------------
/src/pages/NotAuthorized.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { useHistory } from 'react-router-dom'
3 | import { Result, Button } from 'antd'
4 |
5 | const NotAuthorized = () => {
6 | const history = useHistory()
7 | return {
12 | history.push('/login')
13 | }}>Login first!}
14 | />
15 | }
16 |
17 | export default NotAuthorized
18 |
--------------------------------------------------------------------------------
/src/pages/NotFound.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { useHistory } from 'react-router-dom'
3 | import { Result, Button } from 'antd'
4 |
5 | const NotFound = () => {
6 | const history = useHistory()
7 | return {
12 | history.push('/home')
13 | }}>Back Home}
14 | />
15 | }
16 |
17 | export default NotFound
18 |
--------------------------------------------------------------------------------
/src/pages/Post.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Layout from 'components/Layout'
3 | import { Skeleton, message as Message } from 'antd'
4 | import TimeAgo from 'timeago-react'
5 | import { useParams } from 'react-router-dom'
6 | import Axios from 'axios'
7 | import useAuth from 'hooks/use-auth'
8 |
9 | const API_URL = process.env.REACT_APP_API_URL
10 |
11 | const getPost = async (props, callback) => {
12 | const { user, slug } = props
13 | const options = {
14 | headers: {
15 | 'Content-Type': 'multipart/form-data',
16 | Authorization: `Bearer ${user.token}`
17 | },
18 | timeout: 30000
19 | }
20 | try {
21 | const response = await Axios.get(`${API_URL}/api/v1/post/${slug}`, options)
22 | callback(response.data)
23 | } catch (e) {
24 | const data = {
25 | status: 'error',
26 | message: 'Fatal error'
27 | }
28 | callback(data)
29 | }
30 | }
31 |
32 | const Post = () => {
33 | const { slug } = useParams()
34 | const [initial, setInitial] = React.useState(true)
35 | const [post, setPost] = React.useState({})
36 | const { user } = useAuth()
37 |
38 | React.useEffect(() => {
39 | if (initial) {
40 | setInitial(false)
41 | getPost({ user, slug }, response => {
42 | const { status, message, data } = response
43 | if (status === 'success') {
44 | setPost(data)
45 | } else {
46 | Message.error(message)
47 | }
48 | })
49 | }
50 | }, [initial, slug, user])
51 |
52 | console.log(post)
53 | return <>
54 |
55 |
56 | {(post && Object.keys(post).length > 0)
57 | ? <>
58 |
59 |
by {post.user && post.user.username} at
60 |
{post.content}
61 | >
62 | :
63 | }
64 |
65 |
66 | >
67 | }
68 |
69 | export default Post
70 |
--------------------------------------------------------------------------------
/src/pages/Posts.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Layout from 'components/Layout'
3 | import usePost from 'hooks/use-post'
4 | import { List, Button, Skeleton, message as Message } from 'antd'
5 | import TimeAgo from 'timeago-react'
6 |
7 | const Posts = () => {
8 | const {
9 | initial,
10 | loadingPosts,
11 | loading,
12 | visibleLoadMore,
13 | onLoadMore,
14 | error
15 | } = usePost()
16 |
17 | React.useEffect(() => {
18 | if (error && error.length > 0) Message.error(error)
19 | }, [error])
20 |
21 | const loadMore =
22 | !initial && !loading && visibleLoadMore ? (
23 |
31 |
32 |
33 | ) : null
34 |
35 | const getTitle = (item) => {
36 | return <>
37 | {item.id} ~ {item.title}
38 |
39 | by {item.user && item.user.username} at
40 | >
41 | }
42 | return <>
43 |
44 |
45 |
(
52 |
53 |
54 |
55 |
59 |
60 |
61 | )}
62 | />
63 |
64 |
65 | >
66 | }
67 |
68 | export default Posts
69 |
--------------------------------------------------------------------------------
/src/pages/Signup.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Layout from 'components/Layout'
3 | import { Form, Input, Button, message as Message } from 'antd'
4 | import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons'
5 | import { useHistory } from 'react-router-dom'
6 | import useAuth from 'hooks/use-auth'
7 |
8 | const Signup = () => {
9 | const { signup } = useAuth()
10 | const history = useHistory()
11 |
12 | const onFinish = async values => {
13 | const { username, email, password } = values
14 | const { status, message } = await signup({ username, email, password })
15 | if (status === 'success') {
16 | Message.success(message)
17 | history.push('/home')
18 | } else {
19 | Message.error(message)
20 | }
21 | }
22 | return <>
23 |
24 |
80 |
81 | >
82 | }
83 |
84 | export default Signup
85 |
--------------------------------------------------------------------------------
/src/routes.js:
--------------------------------------------------------------------------------
1 | import { lazy } from 'react'
2 |
3 | import Home from 'pages/Home'
4 | const About = lazy(() => import('pages/About'))
5 | const Account = lazy(() => import('pages/Account'))
6 | const Login = lazy(() => import('pages/Login'))
7 | const Signup = lazy(() => import('pages/Signup'))
8 | const ForgotPassword = lazy(() => import('pages/ForgotPassword'))
9 | const Posts = lazy(() => import('pages/Posts'))
10 | const Post = lazy(() => import('pages/Post'))
11 | const NotAuthorized = lazy(() => import('pages/NotAuthorized'))
12 | const NotFound = lazy(() => import('pages/NotFound'))
13 |
14 | const routes = [
15 | {
16 | path: '/post/:slug',
17 | component: Post,
18 | auth: true
19 | },
20 | {
21 | path: '/posts/:page?',
22 | component: Posts,
23 | auth: true
24 | },
25 | {
26 | path: '/forgot-password',
27 | component: ForgotPassword
28 | },
29 | {
30 | path: '/signup',
31 | component: Signup
32 | },
33 | {
34 | path: '/login',
35 | component: Login
36 | },
37 | {
38 | path: '/account',
39 | component: Account,
40 | auth: true
41 | },
42 | {
43 | path: '/about',
44 | component: About
45 | },
46 | {
47 | path: '/home',
48 | component: Home
49 | },
50 | {
51 | exact: true,
52 | path: '/',
53 | component: Home
54 | },
55 | {
56 | path: '/not-authorized',
57 | component: NotAuthorized
58 | },
59 | {
60 | path: '*',
61 | component: NotFound
62 | }
63 | ]
64 |
65 | export default routes
66 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | )
22 |
23 | export function register (config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href)
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config)
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | )
48 | })
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config)
52 | }
53 | })
54 | }
55 | }
56 |
57 | function registerValidSW (swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing
63 | if (installingWorker == null) {
64 | return
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | )
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration)
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.')
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration)
90 | }
91 | }
92 | }
93 | }
94 | }
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error)
98 | })
99 | }
100 |
101 | function checkValidServiceWorker (swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' }
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type')
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload()
117 | })
118 | })
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config)
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | )
128 | })
129 | }
130 |
131 | export function unregister () {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister()
136 | })
137 | .catch(error => {
138 | console.error(error.message)
139 | })
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom/extend-expect'
6 |
--------------------------------------------------------------------------------
/src/store/general.js:
--------------------------------------------------------------------------------
1 | import produce from 'immer'
2 |
3 | const initialState = {
4 | user: {},
5 | guest: true,
6 | appName: 'App Dummy'
7 | }
8 |
9 | const reducer = (currentState, action) => produce(currentState, draft => {
10 | switch (action.type) {
11 | case 'SET': {
12 | const { state, data } = action.payload
13 | draft[state] = data
14 | break
15 | }
16 | default:
17 | return currentState
18 | }
19 | })
20 |
21 | export { initialState, reducer }
22 |
--------------------------------------------------------------------------------
/src/store/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import PropTypes from 'prop-types'
3 | // import { useImmerReducer } from 'use-immer'
4 | import initialStates from './states'
5 | import reducers from './reducers'
6 | import storage from 'utils/storage'
7 |
8 | const states = storage.read(initialStates)
9 |
10 | const contextStates = Object.keys(states).reduce((acc, key) => {
11 | acc[key] = React.createContext()
12 | return acc
13 | }, {})
14 | const contextDispatchs = Object.keys(states).reduce((acc, key) => {
15 | acc[key] = React.createContext()
16 | return acc
17 | }, {})
18 |
19 | function Reducer (key) {
20 | return React.useReducer(reducers[key], states[key])
21 | }
22 |
23 | function SharedProvider ({ children }) {
24 | const Providers = Object.keys(states).reduceRight((acc, key) => {
25 | const stores = Reducer(key)
26 | const contextState = contextStates[key]
27 | const contextDispatch = contextDispatchs[key]
28 | return (
29 |
30 |
31 | {acc}
32 |
33 |
34 | )
35 | }, children)
36 |
37 | return Providers
38 | }
39 |
40 | SharedProvider.propTypes = {
41 | children: PropTypes.node
42 | }
43 |
44 | function useShared (key) {
45 | const state = React.useContext(contextStates[key])
46 | const dispatch = React.useContext(contextDispatchs[key])
47 | storage.write(state, key)
48 | if (state === undefined || dispatch === undefined) {
49 | throw new Error('useShared must be used within a SharedProvider')
50 | }
51 | return [state, dispatch]
52 | }
53 |
54 | export { SharedProvider, useShared }
55 |
--------------------------------------------------------------------------------
/src/store/other.js:
--------------------------------------------------------------------------------
1 | import produce from 'immer'
2 |
3 | const initialState = {
4 | other1: '',
5 | other2: ''
6 | }
7 |
8 | const reducer = (currentState, action) => produce(currentState, draft => {
9 | switch (action.type) {
10 | case 'SET': {
11 | const { state, data } = action.payload
12 | draft[state] = data
13 | break
14 | }
15 | default:
16 | return currentState
17 | }
18 | })
19 |
20 | export { initialState, reducer }
21 |
--------------------------------------------------------------------------------
/src/store/reducers.js:
--------------------------------------------------------------------------------
1 | import { reducer as general } from './general'
2 | import { reducer as other } from './other'
3 | export default { general, other }
4 |
--------------------------------------------------------------------------------
/src/store/states.js:
--------------------------------------------------------------------------------
1 | import { initialState as general } from './general'
2 | import { initialState as other } from './other'
3 | export default { general, other }
4 |
--------------------------------------------------------------------------------
/src/utils/storage.js:
--------------------------------------------------------------------------------
1 |
2 | import LZString from 'lz-string'
3 | const STORAGE_PREFIX = process.env.REACT_APP_STORAGE_PREFIX
4 |
5 | const read = (initialStates, storage = localStorage) => {
6 | try {
7 | return Object.keys(initialStates).reduce((acc, key) => {
8 | const storageKey = STORAGE_PREFIX + key
9 | let newState = initialStates[key]
10 | if (storage.getItem(storageKey) !== null) {
11 | if (process.env.NODE_ENV === 'production') {
12 | newState = JSON.parse(LZString.decompress(storage.getItem(storageKey)))
13 | } else {
14 | newState = JSON.parse(storage.getItem(storageKey))
15 | }
16 | }
17 | acc[key] = newState
18 | return acc
19 | }, {})
20 | } catch (e) {
21 | // console.log(e)
22 | return initialStates
23 | }
24 | }
25 |
26 | const write = (state, key, storage = localStorage) => {
27 | try {
28 | let data = ''
29 | if (process.env.NODE_ENV === 'production') {
30 | data = LZString.compress(JSON.stringify(state))
31 | } else {
32 | data = JSON.stringify(state)
33 | }
34 | storage.setItem((STORAGE_PREFIX + key), data)
35 | } catch (e) {
36 | // console.log(e)
37 | }
38 | }
39 |
40 | export default { read, write }
41 |
--------------------------------------------------------------------------------