App.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. import React, {useState, useEffect, useRef, Component} from 'react';
  2. import logoDefault from './logo.svg';
  3. import cartImg from './cart.svg';
  4. import 'bootstrap/dist/css/bootstrap.min.css';
  5. import './App.scss';
  6. import {Provider, connect} from 'react-redux';
  7. import {createStore, combineReducers, applyMiddleware} from 'redux';
  8. import thunk from 'redux-thunk';
  9. import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
  10. import createHistory from "history/createBrowserHistory";
  11. const defaultRootCats = [
  12. {
  13. "_id": "5dc49f4d5df9d670df48cc64",
  14. "name": "Airconditions"
  15. },
  16. {
  17. "_id": "5dc458985df9d670df48cc47",
  18. "name": " Smartphones"
  19. },
  20. {
  21. "_id": "5dc4b2553f23b553bf354101",
  22. "name": "Крупная бытовая техника"
  23. },
  24. {
  25. "_id": "5dcac1b56d09c45440d14cf8",
  26. "name": "Макароны"
  27. }
  28. ]
  29. const defaultCat ={
  30. "subCategories": null,
  31. "_id": "5dc458985df9d670df48cc47",
  32. "name": " Smartphones",
  33. "goods": [
  34. {
  35. "_id": "61b105f9c750c12ba6ba4524",
  36. "name": "iPhone ",
  37. "price": 1200,
  38. "images": [
  39. {
  40. "url": "images/50842a3af34bfa28be037aa644910d07"
  41. }
  42. ]
  43. },
  44. {
  45. "_id": "61b1069ac750c12ba6ba4526",
  46. "name": "iPhone ",
  47. "price": 1000,
  48. "images": [
  49. {
  50. "url": "images/d12b07d983dac81ccad404582a54d8be"
  51. }
  52. ]
  53. },
  54. {
  55. "_id": "61b23f94c750c12ba6ba472a",
  56. "name": "name1",
  57. "price": 1214,
  58. "images": [
  59. {
  60. "url": null
  61. }
  62. ]
  63. },
  64. {
  65. "_id": "61b23fbac750c12ba6ba472c",
  66. "name": "smart",
  67. "price": 1222,
  68. "images": [
  69. {
  70. "url": "images/871f4e6edbf86c35f70b72dcdebcd8b2"
  71. }
  72. ]
  73. }
  74. ]
  75. }
  76. function jwtDecode(token) {
  77. try {
  78. let decoded = JSON.parse(atob(token.split('.')[1]))
  79. return decoded
  80. } catch (err) {
  81. console.log(err)
  82. }
  83. }
  84. function authReducer(state, {type, token}) {
  85. if (!state) {
  86. if (localStorage.authToken) {
  87. token = localStorage.authToken
  88. type = 'AUTH_LOGIN'
  89. } else {
  90. return {}
  91. }
  92. }
  93. if (type === 'AUTH_LOGIN') {
  94. let payload = jwtDecode(token)
  95. if (typeof payload === 'object') {
  96. localStorage.authToken = token
  97. return {
  98. ...state,
  99. token,
  100. payload
  101. }
  102. } else {
  103. return state
  104. }
  105. }
  106. if (type === 'AUTH_LOGOUT') {
  107. delete localStorage.authToken
  108. return {}
  109. }
  110. return state
  111. }
  112. const actionAuthLogin = (token) => ({type: 'AUTH_LOGIN', token})
  113. const actionAuthLogout = () => ({type: 'AUTH_LOGOUT'})
  114. function cartReducer (state={}, {type, good={}, count=1}) {
  115. if (Object.keys(state).length === 0 && localStorage.cart) {
  116. let currCart = JSON.parse(localStorage.cart)
  117. if (currCart && Object.keys(currCart).length !== 0) {
  118. state = currCart
  119. }
  120. }
  121. const {_id} = good
  122. const types = {
  123. CART_ADD() {
  124. count = +count
  125. if (!count) {
  126. return state
  127. }
  128. let newState = {
  129. ...state,
  130. [_id]: {good, count: (count + (state[_id]?.count || 0)) < 1 ? 1 : count + (state[_id]?.count || 0)}
  131. }
  132. localStorage.cart = JSON.stringify(newState)
  133. return newState
  134. },
  135. CART_CHANGE() {
  136. count = +count
  137. let newState = null
  138. // if (!count) {
  139. // return state
  140. // }
  141. newState = {
  142. ...state,
  143. [_id]: {good, count: count < 1 ? 1 : count}
  144. }
  145. localStorage.cart = JSON.stringify(newState)
  146. return newState
  147. },
  148. CART_REMOVE() {
  149. let { [_id]: removed, ...newState } = state
  150. localStorage.cart = JSON.stringify(newState)
  151. return newState
  152. },
  153. CART_CLEAR() {
  154. localStorage.cart = JSON.stringify({})
  155. return {}
  156. },
  157. }
  158. if (type in types) {
  159. return types[type]()
  160. }
  161. return state
  162. }
  163. const actionCartAdd = (good, count) => ({type: 'CART_ADD', good, count})
  164. const actionCartChange = (good, count) => ({type: 'CART_CHANGE', good, count})
  165. const actionCartRemove = (good) => ({type: 'CART_REMOVE', good})
  166. const actionCartClear = () => ({type: 'CART_CLEAR'})
  167. function promiseReducer(state={}, {type, status, payload, error, name}) {
  168. if (!state) {
  169. return {}
  170. }
  171. if (type === 'PROMISE') {
  172. return {
  173. ...state,
  174. [name]: {
  175. status: status,
  176. payload : payload,
  177. error: error,
  178. }
  179. }
  180. }
  181. return state
  182. }
  183. const actionPending = (name) => ({type: 'PROMISE', status: 'PENDING', name})
  184. const actionResolved = (name, payload) => ({type: 'PROMISE', status: 'RESOLVED', name, payload})
  185. const actionRejected = (name, error) => ({type: 'PROMISE', status: 'REJECTED', name, error})
  186. const actionPromise = (name, promise) => (
  187. async (dispatch) => {
  188. dispatch(actionPending(name))
  189. try {
  190. let data = await promise
  191. dispatch(actionResolved(name, data))
  192. return data
  193. }
  194. catch(error){
  195. dispatch(actionRejected(name, error))
  196. }
  197. }
  198. )
  199. const getGQL = url => (
  200. async (query, variables={}) => {
  201. let obj = await fetch(url, {
  202. method: 'POST',
  203. headers: {
  204. "Content-Type": "application/json",
  205. ...(localStorage.authToken ? {Authorization: "Bearer " + localStorage.authToken} : {})
  206. },
  207. body: JSON.stringify({ query, variables })
  208. })
  209. let a = await obj.json()
  210. if (!a.data && a.errors) {
  211. throw new Error(JSON.stringify(a.errors))
  212. } else {
  213. return a.data[Object.keys(a.data)[0]]
  214. }
  215. }
  216. )
  217. const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua/'
  218. const gql = getGQL(backURL + 'graphql')
  219. const actionOrder = () => (
  220. async (dispatch, getState) => {
  221. let {cart} = getState()
  222. const orderGoods = Object.entries(cart)
  223. .map(([_id, {good, count}]) => ({good: {_id}, count}))
  224. let result = await dispatch(actionPromise('order', gql(`
  225. mutation newOrder($order:OrderInput){
  226. OrderUpsert(order:$order)
  227. { _id total}
  228. }
  229. `, {order: {orderGoods}})))
  230. if (result?._id) {
  231. dispatch(actionCartClear())
  232. }
  233. }
  234. )
  235. const actionLogin = (login, password) => (
  236. actionPromise('login', gql(`query log($login: String, $password: String) {
  237. login(login: $login, password: $password)
  238. }`, {login, password}))
  239. )
  240. const actionFullLogin = (login, password) => (
  241. async (dispatch) => {
  242. let token = await dispatch(actionLogin(login, password))
  243. if (token) {
  244. dispatch(actionAuthLogin(token))
  245. }
  246. }
  247. )
  248. const actionRegister = (login, password) => (
  249. actionPromise('register', gql(`mutation reg($user:UserInput) {
  250. UserUpsert(user:$user) {
  251. _id
  252. }
  253. }
  254. `, {user: {login, password}})
  255. )
  256. )
  257. const actionFullRegister = (login, password) => (
  258. async (dispatch) => {
  259. let regId = await dispatch(actionRegister(login, password))
  260. if (regId) {
  261. dispatch(actionFullLogin(login, password))
  262. }
  263. }
  264. )
  265. const actionRootCats = () => (
  266. actionPromise('rootCats', gql(`query {
  267. CategoryFind(query: "[{\\"parent\\":null}]"){
  268. _id name
  269. }
  270. }`))
  271. )
  272. const actionCatById = (_id) => (
  273. actionPromise('catById', gql(`query catById($q: String){
  274. CategoryFindOne(query: $q){
  275. _id name goods {
  276. _id name price images {
  277. url
  278. }
  279. }
  280. subCategories {
  281. _id name
  282. }
  283. }
  284. }`, {q: JSON.stringify([{_id}])}))
  285. )
  286. const actionGoodById = (_id) => (
  287. actionPromise('goodById', gql(`query goodById($q: String) {
  288. GoodFindOne(query: $q) {
  289. _id name price description images {
  290. url
  291. }
  292. }
  293. }`, {q: JSON.stringify([{_id}])}))
  294. )
  295. const actionGoodsByUser = (_id) => (
  296. actionPromise('goodByUser', gql(`query oUser($query: String) {
  297. OrderFind(query:$query){
  298. _id orderGoods{
  299. price count total good{
  300. _id name categories{
  301. name
  302. }
  303. images {
  304. url
  305. }
  306. }
  307. }
  308. owner {
  309. _id login
  310. }
  311. }
  312. }`,
  313. {query: JSON.stringify([{___owner: _id}])}))
  314. )
  315. const actionGoodFind = (word) => (
  316. actionPromise('goodFind', gql(`query goodById($q: String) {
  317. GoodFind(query: $q) {
  318. _id name price description images {
  319. url
  320. }
  321. }
  322. }`, {q: JSON.stringify([
  323. {
  324. $or: [{title: `/${word}/`}, {description: `/${word}/`}, {name: `/${word}/`}]
  325. },
  326. {
  327. sort: [{title: 1}]
  328. }
  329. ])
  330. }
  331. ))
  332. )
  333. const store = createStore( combineReducers({ promise: promiseReducer,
  334. auth: authReducer,
  335. cart: cartReducer}),
  336. applyMiddleware(thunk))
  337. store.subscribe(() => console.log(store.getState()))
  338. store.dispatch(actionRootCats())
  339. const Logo = ({logo=logoDefault}) => (
  340. <Link to='/' className="Logo">
  341. <img src={logo} />
  342. </Link>
  343. )
  344. const Koshik = ({cart}) => {
  345. let count = 0;
  346. let sum = Object.entries(cart).map(([, val]) => val.count)
  347. count = sum.reduce((a, b) => a + b, 0)
  348. //перебрать cart, посчитать суммарный count
  349. return (
  350. <Link to='/cart' className='Koshik'>
  351. <img src={cartImg} />
  352. {count}
  353. </Link>
  354. )
  355. }
  356. const CKoshik = connect(({cart}) => ({cart}))(Koshik)
  357. const GreetContainer = ({user: {id, login}}) => {
  358. if (id && login) {
  359. return (
  360. <div>
  361. <div>
  362. ПРИВЕТ, {login}
  363. </div>
  364. <Link to={`/orders/${id}`} >
  365. Мои заказы
  366. </Link>
  367. </div>
  368. )
  369. } else {
  370. return (<></>)
  371. }
  372. }
  373. const CGreetContainer = connect(state => ({user: state.auth.payload?.sub || {}}))(GreetContainer)
  374. const Header = ({logo=logoDefault}) => (
  375. <header className="bg-light">
  376. <div className="leftBlock">
  377. <Logo logo={logo} />
  378. </div>
  379. <div className="rightBlock">
  380. <CKoshik />
  381. <CGreetContainer />
  382. </div>
  383. </header>
  384. )
  385. const RootCategory = ({cat:{_id, name}={}}) => (
  386. <Link to={`/category/${_id}`}
  387. className="catBtn list-group-item list-group-item-action list-group-item-light">
  388. {name}
  389. </Link>
  390. )
  391. const RootCategories = ({cats=defaultRootCats}) => (
  392. <div className='RootCategories list-group linkList'>
  393. {cats.map(cat => <RootCategory cat={cat} />)}
  394. </div>
  395. )
  396. const CRootCategories = connect(state => ({cats: state.promise.rootCats?.payload || []}))(RootCategories)
  397. const LogoutBTn = ({onLogout}) => (
  398. <button className='logoutBtn btn btn-primary'
  399. onClick={() => onLogout()}>
  400. Logout
  401. </button>
  402. )
  403. const CLogoutBTn = connect(null, {onLogout: actionAuthLogout})(LogoutBTn)
  404. const Aside = () => (
  405. <aside className="bg-light">
  406. <div className='LoginBlock'>
  407. <Link to='/login' className='loginBtn btn btn-primary'>Login</Link>
  408. <Link to='/register' className='registerBtn btn btn-primary'>Register</Link>
  409. <CLogoutBTn />
  410. </div>
  411. <CRootCategories />
  412. </aside>
  413. )
  414. const Content = ({children}) => (
  415. <div className='Content'>
  416. {children}
  417. </div>
  418. )
  419. const SubCategory = ({cat:{_id, name}={}}) => (
  420. <Link to={`/category/${_id}`}
  421. className='list-group-item list-group-item-action list-group-item-primary linkItem'>
  422. {name}
  423. </Link>
  424. )
  425. const SubCategories = ({cats}) => (
  426. <div className="CatsList list-group linkList">
  427. {cats.map(cat => <SubCategory cat={cat} />)}
  428. </div>
  429. )
  430. const GoodCard = ({good:{_id, name, price, images}={}, onCartAdd}) => (
  431. <div className='GoodCard card'>
  432. {images && images[0] && images[0].url &&
  433. <img className='card-img-top' src={backURL + '/' + images[0].url} />}
  434. <div className="card-body">
  435. <h4 className="card-title">{name}</h4>
  436. <h5>{price} грн</h5>
  437. <button className='btn btn-primary'
  438. onClick={() => onCartAdd({_id, name, price, images})}>В корзину</button>
  439. <Link className='btn btn-success'
  440. to={`/good/${_id}`}>Подробнее</Link>
  441. </div>
  442. </div>
  443. )
  444. const CGoodCard = connect(null, {onCartAdd: actionCartAdd})(GoodCard)
  445. const Category = ({cat:{_id, name, goods, subCategories}=defaultCat}) => (
  446. <div className='Category'>
  447. <h1>{name}</h1>
  448. {subCategories && <SubCategories cats={subCategories} />}
  449. <div className='GoodCards'>
  450. {(goods || []).map(good => <CGoodCard good={good}/>)}
  451. </div>
  452. </div>
  453. )
  454. const CCategory = connect(state => ({cat: state.promise.catById?.payload}))(Category)
  455. const GoodInCart = ({item: {count, good: {_id, name, price, images}}, onCartChange, onCartRemove, onCartAdd}) => {
  456. const [goodCount, setGoodCount] = useState(count)
  457. return (
  458. <div className='CartCard card'>
  459. <div className="card-header">
  460. <h4 className="card-title">{name}</h4>
  461. </div>
  462. {images && images[0] && images[0].url &&
  463. <img className="card-img-top" src={backURL + '/' + images[0].url} />}
  464. <div className="card-body">
  465. <p>{count} шт</p>
  466. <p>{price} грн</p>
  467. <h6>Итого: {count*price} грн</h6>
  468. <button className="btn btn-success"
  469. onClick={() => { setGoodCount((count === 1 ) ? 1 : count - 1);
  470. onCartAdd({_id, name, price, images}, -1) }}>-</button>
  471. <input onBlur={() => onCartChange({_id, name, price, images}, goodCount)}
  472. onInput={(e) => setGoodCount(e.currentTarget.value)}
  473. // onInput={(e) => onCartChange({_id, name, price, images}, e.currentTarget.value)}
  474. value={goodCount} type="number"/>
  475. <button className="btn btn-success"
  476. onClick={() => { setGoodCount(count + 1);
  477. onCartAdd({_id, name, price, images}) }}>+</button>
  478. <button className="btn btn-success delBtn"
  479. onClick={() => onCartRemove({_id, name, price, images})}>Удалить</button>
  480. </div>
  481. </div>
  482. )
  483. }
  484. const CGoodInCart = connect(null, { onCartChange: actionCartChange,
  485. onCartRemove: actionCartRemove,
  486. onCartAdd: actionCartAdd})(GoodInCart)
  487. const Cart = ({cart, user, onCartClear, onOrderSend}) => {
  488. let total = 0
  489. if (cart.length !== 0) {
  490. let countes = Object.entries(cart).map(([, val]) => val.count)
  491. let prices = Object.entries(cart).map(([, val]) => val.good.price)
  492. let sum = countes.map((count, index) => prices[index] * count)
  493. total = sum.reduce((a, b) => a + b)
  494. }
  495. return (
  496. <div className='Cart'>
  497. {cart.length === 0 ? <h5>Корзина пуста</h5> :
  498. <button className='btn btn-primary'
  499. onClick={() => onCartClear()}>
  500. Очистить корзину
  501. </button>}
  502. <div className='CartBlock'>
  503. {cart.map(item => <CGoodInCart item={item}/>)}
  504. </div>
  505. {cart.length === 0 ? <></> :
  506. <>
  507. <h5>Всего к оплате: {total} грн</h5>
  508. <button className='btn btn-primary'
  509. onClick={() => onOrderSend()}
  510. disabled={user ? false : true}>
  511. Оформить заказ
  512. </button>
  513. </>}
  514. </div>
  515. )
  516. }
  517. const CCart = connect(state => ({ cart: Object.values(state.cart) || [],
  518. user: state.auth.payload || null}),
  519. { onCartClear: actionCartClear,
  520. onOrderSend: actionOrder})(Cart)
  521. const LoginForm = ({onLogin}) => {
  522. const [login, setLogin] = useState("")
  523. const [pass, setPass] = useState("")
  524. return (
  525. <div className='LoginForm form'>
  526. <div className="mb-3">
  527. <label className="form-label">Логин</label>
  528. <input className="form-input form-control"
  529. type="text"style={ {backgroundColor: (login.length === 0) ? '#f00b' : '#fff'} }
  530. value={login} onChange={(e) => setLogin(e.target.value)}/>
  531. </div>
  532. <div className="mb-3">
  533. <label className="form-label">Пароль</label>
  534. <input className="form-input form-control"
  535. type="password" style={ {backgroundColor: (pass.length === 0) ? '#f00b' : '#fff'} }
  536. value={pass} onChange={(e) => setPass(e.target.value)}/>
  537. </div>
  538. <button className="btn btn-primary"
  539. onClick={() => { onLogin(login,pass);
  540. setPass('')
  541. }}
  542. disabled={(login.length !== 0 && pass.length !== 0) ? false : true}>Войти</button>
  543. </div>
  544. )
  545. }
  546. const CLoginForm = connect(null, {onLogin: actionFullLogin})(LoginForm)
  547. const RegisterForm = ({onRegister}) => {
  548. const [login, setLogin] = useState("")
  549. const [pass, setPass] = useState("")
  550. return (
  551. <div className='RegisterForm form'>
  552. <div className="mb-3">
  553. <label className="form-label">Логин</label>
  554. <input className="form-input form-control"
  555. type="text" style={ {backgroundColor: (login.length === 0) ? '#f00b' : '#fff'} }
  556. value={login} onChange={(e) => setLogin(e.target.value)}/>
  557. </div>
  558. <div className="mb-3">
  559. <label className="form-label">Пароль</label>
  560. <input className="form-input form-control"
  561. type="password" style={ {backgroundColor: (pass.length === 0) ? '#f00b' : '#fff'} }
  562. value={pass} onChange={(e) => setPass(e.target.value)}/>
  563. </div>
  564. <button className="btn btn-primary"
  565. onClick={() => { onRegister(login,pass);
  566. setPass('')
  567. }}
  568. disabled={(login.length !== 0 && pass.length !== 0) ? false : true}>Зарегистрироваться</button>
  569. </div>
  570. )
  571. }
  572. const CRegisterForm = connect(null, {onRegister: actionFullRegister})(RegisterForm)
  573. const PageMain = () => (
  574. <h1>Главная страница</h1>
  575. )
  576. const PageCategory = ({match:{params:{_id}}, getData, history}) => {
  577. useEffect(() => {
  578. getData(_id)
  579. },[_id])
  580. return (
  581. <CCategory />
  582. )
  583. }
  584. const CPageCategory = connect(null, {getData: actionCatById})(PageCategory)
  585. const ThisGood = ({good:{_id, name, price, images, description}={}, onCartAdd}) => (
  586. <div className='GoodPage'>
  587. <h2>{name}</h2>
  588. {images && images[0] && images[0].url && <img src={backURL + '/' + images[0].url} />}
  589. <div>
  590. <h6>{description}</h6>
  591. <strong>Цена - {price} грн</strong>
  592. </div>
  593. <button className="btn btn-success"
  594. onClick={() => onCartAdd({_id, name, price, images})}>В корзину</button>
  595. </div>
  596. )
  597. const CThisGood = connect( state => ({good: state.promise.goodById?.payload}),
  598. {onCartAdd: actionCartAdd})(ThisGood)
  599. const PageGood = ({match:{params:{_id}}, getData}) => {
  600. useEffect(() => {
  601. getData(_id)
  602. },[_id])
  603. return (
  604. <>
  605. <CThisGood />
  606. </>
  607. )
  608. }
  609. const CPageGood = connect(null, {getData: actionGoodById})(PageGood)
  610. // на текущий момент функция отображает только 100 последних заказов
  611. // подсчет потраченных средств нужно реализовать для всех заказов
  612. // но при этом сразу отображать только 100 последних
  613. const OrderedGood = ({goodOrder:{price, count, total, good}={}}) => {
  614. if (price !== null && count !== null && total !== null && good !== null) {
  615. const {_id, name, images} = good
  616. return (
  617. <div className='OrderCard card'>
  618. {images && images[0] && images[0].url &&
  619. <img className='card-img-top' src={backURL + '/' + images[0].url} />}
  620. <div className="card-body">
  621. <h4 className="card-title">{name}</h4>
  622. <h6>
  623. Куплено: {count} по {price} грн.
  624. </h6>
  625. <h6>
  626. Итого: {total} грн
  627. </h6>
  628. <Link className="btn btn-primary"
  629. to={`/good/${_id}`}>Подробнее</Link>
  630. </div>
  631. </div>
  632. )
  633. } else {
  634. return <></>
  635. }
  636. }
  637. const Orders = ({orders}) => (
  638. <div className='Orders'>
  639. {/* <h3>Всего потрачено: {totalMoney} грн</h3> */}
  640. <div className='OrderCards'>
  641. { orders.map(order =>
  642. (order.orderGoods ? order.orderGoods: []).map(goodOrder =>
  643. <OrderedGood goodOrder={goodOrder}/>))}
  644. </div>
  645. </div>
  646. )
  647. const COrders = connect(state => ({orders: state.promise.goodByUser?.payload || []}))(Orders)
  648. const PageOrders = ({match:{params:{_id}}, getData}) => {
  649. useEffect(() => {
  650. getData(_id)
  651. },[_id])
  652. return (
  653. <>
  654. <COrders />
  655. </>
  656. )
  657. }
  658. const CPageOrders = connect(null, {getData: actionGoodsByUser})(PageOrders)
  659. const Page404 = () => (
  660. <h1>PAGE НЭМА </h1>
  661. )
  662. const Main = () => (
  663. <main>
  664. <Aside />
  665. <Content>
  666. <Redirect from="/main" to="/" />
  667. <Switch>
  668. <Route path="/" component={PageMain} exact />
  669. <Route path="/category/:_id" component={CPageCategory} />
  670. <Route path="/good/:_id" component={CPageGood} />
  671. <Route path="/cart" component={CCart} />
  672. <Route path="/login" component={CLoginForm} />
  673. <Route path="/register" component={CRegisterForm} />
  674. <Route path="/orders/:_id" component={CPageOrders} />
  675. <Route path="*" component={Page404} />
  676. </Switch>
  677. </Content>
  678. </main>
  679. )
  680. const Footer = ({logo=logoDefault}) => (
  681. <footer>
  682. <Logo logo={logo} />
  683. </footer>
  684. )
  685. const history = createHistory()
  686. function App() {
  687. return (
  688. <Router history={history}>
  689. <Provider store={store}>
  690. <div className="App">
  691. <Header />
  692. <Main />
  693. <Footer />
  694. </div>
  695. </Provider>
  696. </Router>
  697. )
  698. }
  699. export default App;