bolvanka.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. function createStore(reducer) {
  2. let state = reducer(undefined, {}) //стартовая инициализация состояния, запуск редьюсера со state === undefined
  3. let cbs = [] //массив подписчиков
  4. const getState = () => state //функция, возвращающая переменную из замыкания
  5. const subscribe = cb => (cbs.push(cb), //запоминаем подписчиков в массиве
  6. () => cbs = cbs.filter(c => c !== cb)) //возвращаем функцию unsubscribe, которая удаляет подписчика из списка
  7. const dispatch = action => {
  8. if (typeof action === 'function') { //если action - не объект, а функция
  9. return action(dispatch, getState) //запускаем эту функцию и даем ей dispatch и getState для работы
  10. }
  11. const newState = reducer(state, action) //пробуем запустить редьюсер
  12. if (newState !== state) { //проверяем, смог ли редьюсер обработать action
  13. state = newState //если смог, то обновляем state
  14. for (let cb of cbs) cb(state) //и запускаем подписчиков
  15. }
  16. }
  17. return {
  18. getState, //добавление функции getState в результирующий объект
  19. dispatch,
  20. subscribe //добавление subscribe в объект
  21. }
  22. }
  23. function combineReducers(reducers) {
  24. function totalReducer(state = {}, action) {
  25. const newTotalState = {}
  26. for (const [reducerName, reducer] of Object.entries(reducers)) {
  27. const newSubState = reducer(state[reducerName], action)
  28. if (newSubState !== state[reducerName]) {
  29. newTotalState[reducerName] = newSubState
  30. }
  31. }
  32. if (Object.keys(newTotalState).length) {
  33. return { ...state, ...newTotalState }
  34. }
  35. return state
  36. }
  37. return totalReducer
  38. }
  39. const reducers = {
  40. promise: promiseReducer, //допилить много имен для многих промисо
  41. //auth: authReducer, //часть предыдущего ДЗ
  42. //cart: cartReducer, //часть предыдущего ДЗ
  43. }
  44. const totalReducer = combineReducers(reducers)
  45. function promiseReducer(state = {}, { type, status, payload, error }) {
  46. if (type === 'PROMISE') {
  47. //имена добавить
  48. return { status, payload, error }
  49. }
  50. return state
  51. }
  52. //имена добавить
  53. const actionPending = () => ({ type: 'PROMISE', status: 'PENDING' })
  54. const actionFulfilled = payload => ({ type: 'PROMISE', status: 'FULFILLED', payload })
  55. const actionRejected = error => ({ type: 'PROMISE', status: 'REJECTED', error })
  56. //имена добавить
  57. const actionPromise = promise =>
  58. async dispatch => {
  59. dispatch(actionPending()) //сигнализируем redux, что промис начался
  60. try {
  61. const payload = await promise //ожидаем промиса
  62. dispatch(actionFulfilled(payload)) //сигнализируем redux, что промис успешно выполнен
  63. return payload //в месте запуска store.dispatch с этим thunk можно так же получить результат промиса
  64. }
  65. catch (error) {
  66. dispatch(actionRejected(error)) //в случае ошибки - сигнализируем redux, что промис несложился
  67. }
  68. }
  69. const store = createStore(totalReducer) //не забудьте combineReducers если он у вас уже есть
  70. store.subscribe(() => console.log(store.getState()))
  71. const drawPeople = (state) => {
  72. const [, route] = location.hash.split('/')
  73. if (route !== 'people') return
  74. const { status, payload, error } = store.getState().promise//.имя другое
  75. if (status === 'PENDING') {
  76. main.innerHTML = `<img src='https://cdn.dribbble.com/users/63485/screenshots/1309731/infinite-gif-preloader.gif' />`
  77. }
  78. if (status === 'FULFILLED') {
  79. const { name, mass, eye_color, films } = payload
  80. main.innerHTML = `<h1>${name}</h1>
  81. <section>ЖЫРНОСТЬ: ${mass}кг</section>
  82. <section style="color: ${eye_color}">Цвет глаз</section>
  83. `
  84. for (const filmUrl of films) {
  85. const filmId = filmUrl.split('/films/')[1].slice(0, -1)
  86. main.innerHTML += `<a href="#/films/${filmId}">Фильм №${filmId}</a>`
  87. }
  88. }
  89. }
  90. store.subscribe(drawPeople)
  91. store.subscribe(() => {
  92. const [, route] = location.hash.split('/')
  93. if (route !== 'films') return
  94. const { status, payload, error } = store.getState().promise//.имя одно
  95. if (status === 'PENDING') {
  96. main.innerHTML = `<img src='https://cdn.dribbble.com/users/63485/screenshots/1309731/infinite-gif-preloader.gif' />`
  97. }
  98. if (status === 'FULFILLED') {
  99. const { title, opening_crawl, characters } = payload
  100. main.innerHTML = `<h1>${title}</h1>
  101. <p>${opening_crawl}</p>
  102. `
  103. for (const peopleUrl of characters) {
  104. const peopleId = peopleUrl.split('/people/')[1].slice(0, -1)
  105. main.innerHTML += `<a href="#/people/${peopleId}">Герой №${peopleId}</a>`
  106. }
  107. }
  108. })
  109. const actionGetPeople = id => //имя другое
  110. actionPromise(fetch(`https://swapi.dev/api/people/${id}`).then(res => res.json()))
  111. const actionGetFilm = id =>
  112. actionPromise(fetch(`https://swapi.dev/api/films/${id}`).then(res => res.json()))
  113. const actionSomePeople = () =>
  114. actionPromise(fetch(`https://swapi.dev/api/people/`).then(res => res.json()))
  115. store.dispatch(actionSomePeople())
  116. store.subscribe(() => {
  117. const { status, payload, error } = store.getState().promise//.имя третье
  118. if (status === 'FULFILLED' && payload.results) {
  119. aside.innerHTML = ''
  120. for (const { url: peopleUrl, name } of payload.results) {
  121. const peopleId = peopleUrl.split('/people/')[1].slice(0, -1)
  122. aside.innerHTML += `<a href="#/people/${peopleId}">${name}</a>`
  123. }
  124. }
  125. })
  126. window.onhashchange = () => {
  127. const [, route, _id] = location.hash.split('/')
  128. const routes = {
  129. people() {
  130. console.log('People', _id)
  131. store.dispatch(actionGetPeople(_id))
  132. },
  133. films() {
  134. store.dispatch(actionGetFilm(_id))
  135. },
  136. //category() {
  137. //store.dispatch(actionCategoryById(_id))
  138. //},
  139. //good(){
  140. ////тут был store.dispatch goodById
  141. //console.log('good', _id)
  142. //},
  143. login() {
  144. console.log('А ТУТ ЩА ДОЛЖНА БЫТЬ ФОРМА ЛОГИНА')
  145. //нарисовать форму логина, которая по нажатию кнопки Login делает store.dispatch(actionFullLogin(login, password))
  146. },
  147. //register(){
  148. ////нарисовать форму регистрации, которая по нажатию кнопки Login делает store.dispatch(actionFullRegister(login, password))
  149. //},
  150. }
  151. if (route in routes) {
  152. routes[route]()
  153. }
  154. }
  155. window.onhashchange()