24_practic_Redux_async.html 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <button id="A">A</button>
  10. <button id="B">B</button>
  11. <h1 id="Cart"></h1>
  12. <script>
  13. function createStore(reducer) {
  14. let state = reducer(undefined, {});
  15. let cbs = [];
  16. function dispatch(action) {
  17. if (typeof action === "function") {
  18. return action(dispatch);
  19. }
  20. let newState = reducer(state, action);
  21. if (state !== newState) {
  22. state = newState;
  23. for (let cb of cbs) cb();
  24. }
  25. }
  26. return {
  27. getState() {
  28. return state;
  29. },
  30. dispatch,
  31. subscribe(cb) {
  32. cbs.push(cb);
  33. return () => {
  34. cbs = cbs.filter(
  35. (someElement) => someElement !== cb
  36. );
  37. };
  38. },
  39. };
  40. }
  41. function cartReducer(state = {}, { type, id, count }) {
  42. if (type === "CART_ADD") {
  43. return {
  44. ...state,
  45. [id]: count + (state[id] || 0),
  46. };
  47. }
  48. if (type === "CART_DELETE") {
  49. const { [id]: skip, ...newState } = state;
  50. return newState;
  51. }
  52. return state;
  53. }
  54. function promiseReducer(
  55. state = {},
  56. { type, status, payload, error, name }
  57. ) {
  58. if (type === "PROMISE") {
  59. return { ...state, [name]: { status, payload, error } };
  60. }
  61. return state;
  62. }
  63. const store = createStore(promiseReducer);
  64. store.subscribe(() => console.log(store.getState()));
  65. // store.subscribe( ()=> {
  66. // Cart.innerText = store.getState().delay3.status
  67. // })
  68. const actionPromisePending = (name) => ({
  69. name,
  70. type: "PROMISE",
  71. status: "PENDING",
  72. });
  73. const actionPromiseResolved = (name, payload) => ({
  74. name,
  75. type: "PROMISE",
  76. status: "RESOLVED",
  77. payload,
  78. error: undefined,
  79. });
  80. const actionPromiseRejected = (name, error) => ({
  81. name,
  82. type: "PROMISE",
  83. status: "REJECTED",
  84. payload: undefined,
  85. error,
  86. });
  87. const delaySec = (sec) =>
  88. new Promise((ok) => setTimeout(() => ok(sec), sec * 1000));
  89. // store.dispatch(actionPromisePending('delay'))
  90. // delaySec(3).then(payload => store.dispatch(actionPromiseResolved('delay', payload)),
  91. // error => store.dispatch(actionPromiseRejected('delay', error))
  92. // );
  93. function actionPromise(name, promise) {
  94. return async (dispatch) => {
  95. dispatch(actionPromisePending(name));
  96. try {
  97. let payload = await promise;
  98. dispatch(actionPromiseResolved(name, payload));
  99. return payload;
  100. } catch (e) {
  101. dispatch(actionPromiseRejected(name, e));
  102. }
  103. };
  104. }
  105. store.dispatch(actionPromise("delay3", delaySec(3)));
  106. store.dispatch(actionPromise("delay5", delaySec(5)));
  107. const getGQL = (url) => (query, variables = {}) => {
  108. return fetch(url, {
  109. method: "POST",
  110. headers: {
  111. Accept: "application/json",
  112. "Content-Type": "application/json",
  113. ...(localStorage.authToken
  114. ? {
  115. Authorization: `Bearer ${localStorage.authToken}`,
  116. }
  117. : {}),
  118. },
  119. body: JSON.stringify({ query, variables }),
  120. }).then((res) => res.json());
  121. };
  122. let gql = getGQL(
  123. "http://shop-roles.asmer.fs.a-level.com.ua/graphql"
  124. );
  125. function actionLogin(login, password) {
  126. return actionPromise(
  127. "login",
  128. gql(
  129. `query login($login:String, $password:String) {
  130. login(login:$login, password:$password)
  131. }`,
  132. { login, password }
  133. )
  134. );
  135. }
  136. // store.dispatch(actionLogin("qqq", "123")); // View событие
  137. // const actionCartAdd = (id, count = 1) => ({type:"CART_ADD", id, count});
  138. // const actionCartDelete = (id) => ({type:"CART_DELETE", id});
  139. // A.onclick = () => {store.dispatch(actionCartAdd('A'))}
  140. // B.onclick = () => {store.dispatch(actionCartAdd('B'))}
  141. // store.dispatch({type:"CART_ADD", id: "A", count: 3})
  142. // store.dispatch({type:"CART_ADD", id: "B", count: 4})
  143. // store.dispatch({type:"CART_ADD", id: "C", count: 5})
  144. // store.dispatch({type:"CART_DELETE", id: "B"})
  145. </script>
  146. </body>
  147. </html>