24_practic_Redux_async2.html 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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>25</title>
  7. </head>
  8. <body>
  9. <button id="A">A</button>
  10. <button id="B">B</button>
  11. <pre id="Cart"></pre>
  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. console.log("3 reduser", name, status);
  60. return { ...state, [name]: { status, payload, error } };
  61. }
  62. return state;
  63. }
  64. const store = createStore(promiseReducer);
  65. store.subscribe(() => console.log(store.getState()));
  66. store.subscribe(() => {
  67. Cart.innerText += JSON.stringify(store.getState(), null, 4);
  68. console.log("4 subscribe");
  69. });
  70. const actionPromisePending = (name) => ({
  71. name,
  72. type: "PROMISE",
  73. status: "PENDING",
  74. });
  75. const actionPromiseResolved = (name, payload) => ({
  76. name,
  77. type: "PROMISE",
  78. status: "RESOLVED",
  79. payload,
  80. error: undefined,
  81. });
  82. const actionPromiseRejected = (name, error) => ({
  83. name,
  84. type: "PROMISE",
  85. status: "REJECTED",
  86. payload: undefined,
  87. error,
  88. });
  89. const delaySec = (sec) =>
  90. new Promise((ok) => setTimeout(() => ok(sec), sec * 1000));
  91. // store.dispatch(actionPromisePending('delay'))
  92. // delaySec(3).then(payload => store.dispatch(actionPromiseResolved('delay', payload)),
  93. // error => store.dispatch(actionPromiseRejected('delay', error))
  94. // );
  95. function actionPromise(name, promise) {
  96. return async (dispatch) => {
  97. console.log("2 action pending", name);
  98. dispatch(actionPromisePending(name));
  99. try {
  100. let payload = await promise;
  101. console.log("3 resolved");
  102. dispatch(actionPromiseResolved(name, payload));
  103. return payload;
  104. } catch (e) {
  105. console.log("3 rejected");
  106. dispatch(actionPromiseRejected(name, e));
  107. }
  108. };
  109. }
  110. console.log("1 start timer");
  111. store.dispatch(actionPromise("delay3", delaySec(3)));
  112. store.dispatch(actionPromise("delay5", delaySec(5)));
  113. const getGQL = (url) => (query, variables = {}) => {
  114. return fetch(url, {
  115. method: "POST",
  116. headers: {
  117. Accept: "application/json",
  118. "Content-Type": "application/json",
  119. ...(localStorage.authToken
  120. ? {
  121. Authorization: `Bearer ${localStorage.authToken}`,
  122. }
  123. : {}),
  124. },
  125. body: JSON.stringify({ query, variables }),
  126. }).then((res) => res.json());
  127. };
  128. let gql = getGQL(
  129. "http://shop-roles.asmer.fs.a-level.com.ua/graphql"
  130. );
  131. function actionLogin(login, password) {
  132. return actionPromise(
  133. "login",
  134. gql(
  135. `query login($login:String, $password:String) {
  136. login(login:$login, password:$password)
  137. }`,
  138. { login, password }
  139. )
  140. );
  141. }
  142. // store.dispatch(actionLogin("qqq", "123")); // View событие
  143. function actionRegister(login, password) {
  144. return actionPromise(
  145. "register",
  146. gql(
  147. `mutation newUser($login: String, $password: String) {
  148. UserUpsert(user: {login: $login, password: $password}) {
  149. _id
  150. createdAt
  151. }
  152. }`,
  153. { login, password }
  154. )
  155. );
  156. }
  157. function actionRegAndLogin(login, password) {
  158. return async (dispatch) => {
  159. let regData = await dispatch(
  160. actionRegister(login, password)
  161. );
  162. if (regData.data.UserUpsert) {
  163. let logData = await dispatch(
  164. actionLogin(login, password)
  165. );
  166. console.log(logData);
  167. }
  168. };
  169. }
  170. store.dispatch(actionRegAndLogin("qqq10", "123"));
  171. // const actionCartAdd = (id, count = 1) => ({type:"CART_ADD", id, count});
  172. // const actionCartDelete = (id) => ({type:"CART_DELETE", id});
  173. // A.onclick = () => {store.dispatch(actionCartAdd('A'))}
  174. // B.onclick = () => {store.dispatch(actionCartAdd('B'))}
  175. // store.dispatch({type:"CART_ADD", id: "A", count: 3})
  176. // store.dispatch({type:"CART_ADD", id: "B", count: 4})
  177. // store.dispatch({type:"CART_ADD", id: "C", count: 5})
  178. // store.dispatch({type:"CART_DELETE", id: "B"})
  179. </script>
  180. </body>
  181. </html>