Browse Source

<Market done

Illia Kozyr 2 years ago
parent
commit
e8b744dff3
3 changed files with 20 additions and 102 deletions
  1. 0 12
      Market GraphQL + Redux/index2.html
  2. 20 19
      Market GraphQL + Redux/script.js
  3. 0 71
      Market GraphQL + Redux/test.js

+ 0 - 12
Market GraphQL + Redux/index2.html

@@ -1,12 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
-    <meta charset="UTF-8">
-    <meta http-equiv="X-UA-Compatible" content="IE=edge">
-    <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <title>Document</title>
-</head>
-<body>
-    <script src="test.js"></script>
-</body>
-</html>

+ 20 - 19
Market GraphQL + Redux/script.js

@@ -392,8 +392,8 @@ bPoput.id = "b-popup";
 const bPoputContainer = document.createElement("div");
 bPoputContainer.className = "b-popup-content";
 bPoputContainer.id = "b-popup-content";
-const buttonGoodDeleteBlock = document.createElement('div')
-buttonGoodDeleteBlock.id = "buttonGoodDeleteBlock"
+const buttonGoodDeleteBlock = document.createElement("div");
+buttonGoodDeleteBlock.id = "buttonGoodDeleteBlock";
 
 const buttonCloseCart = document.createElement("button");
 buttonCloseCart.innerText = `×`;
@@ -408,25 +408,21 @@ shoppingCart.onclick = () => {
 };
 
 bPoputContainer.append(buttonGoodDeleteBlock);
-buttonGoodDeleteBlock.append(buttonGoodDelete)
+buttonGoodDeleteBlock.append(buttonGoodDelete);
 bPoputContainer.append(buttonCloseCart);
 
-
 const divToCardBlock = document.createElement("div");
 
-
 store.subscribe(() => {
-    divToCardBlock.innerHTML = ""
+    divToCardBlock.innerHTML = "";
     toCartById = store.getState().cart;
+    let countSum = 0;
     for (let value of Object.values(toCartById)) {
-
-        
         const { count, good } = value;
-        console.log(count, "its cartbyid")
+        countSum += count;
 
         divToCardBlock.id = "divToCartBlock";
         const divToCart = document.createElement("div");
-        
 
         const goodByIdImage = document.createElement("img");
         const goodByIdName = document.createElement("h2");
@@ -450,8 +446,12 @@ store.subscribe(() => {
         goodByIdImage.src = `${backendURLNotGraphQL}/${value.good.images[0].url}`;
         goodByIdName.innerText = good.name;
         goodByIdCount.innerText = count;
+
+        
     }
 
+    shoppingCart.innerHTML = "Cart: " + countSum;
+
     buttonCloseCart.onclick = () => {
         var parent = document.getElementById("header");
         var child = document.getElementById("b-popup");
@@ -468,10 +468,10 @@ store.subscribe(() => {
 
 buttonGoodDelete.onclick = () => {
     store.dispatch(actionCartClear());
-    let a = document.getElementById('divToCartBlock')
+    let a = document.getElementById("divToCartBlock");
     a.innerHTML = "";
-    let b = document.getElementById('shoppingCart')
-    b.innerHTML = "Cart"
+    let b = document.getElementById("shoppingCart");
+    b.innerHTML = "Cart";
 };
 
 const buyButtom = document.createElement("button");
@@ -482,7 +482,6 @@ const textBlock = document.createElement("div");
 const flexBlock = document.createElement("div");
 const productDescription = document.createElement("p");
 
-let number = 0;
 store.subscribe(() => {
     const goodById =
         store.getState().promise.GoodFineOne?.payload?.data.GoodFindOne;
@@ -494,7 +493,6 @@ store.subscribe(() => {
             element.removeChild(element.firstChild);
         }
         const { name, price, description, images } = goodById;
-       
 
         flexBlock.id = "flexBlock";
 
@@ -518,17 +516,20 @@ store.subscribe(() => {
         textBlock.append(productDescription);
 
         buyButtom.id = "buyButtom";
-        buyButtom.innerHTML = "Buy";
+        buyButtom.innerHTML = "Add to cart";
         textBlock.append(buyButtom);
         buyButtom.onclick = () => {
             store.dispatch(actionCartAdd(goodById));
-            let a = document.getElementById('shoppingCart')
-            number += 1
-            a.innerHTML = "Cart: " + number;
         };
+       
+        
     }
 });
 
+
+
+
+
 store.subscribe(() => {
     const catById =
         store.getState().promise.catById?.payload?.data.CategoryFindOne;

+ 0 - 71
Market GraphQL + Redux/test.js

@@ -1,71 +0,0 @@
-function createStore(reducer) {
-    let state = reducer(undefined, {}); //стартовая инициализация состояния, запуск редьюсера со state === undefined
-    let cbs = []; //массив подписчиков
-
-    const getState = () => state; //функция, возвращающая переменную из замыкания
-    const subscribe = (cb) => (
-        cbs.push(cb), //запоминаем подписчиков в массиве
-        () => (cbs = cbs.filter((c) => c !== cb))
-    ); //возвращаем функцию unsubscribe, которая удаляет подписчика из списка
-
-    const dispatch = (action) => {
-        if (typeof action === "function") {
-            //если action - не объект, а функция
-            return action(dispatch, getState); //запускаем эту функцию и даем ей dispatch и getState для работы
-        }
-        const newState = reducer(state, action); //пробуем запустить редьюсер
-        if (newState !== state) {
-            //проверяем, смог ли редьюсер обработать action
-            state = newState; //если смог, то обновляем state
-            for (let cb of cbs) cb(); //и запускаем подписчиков
-        }
-    };
-
-    return {
-        getState, //добавление функции getState в результирующий объект
-        dispatch,
-        subscribe, //добавление subscribe в объект
-    };
-}
-
-function countReducer(state = {count: 0}, {type}){
-    if(type === "COUNT_INC"){
-        return {
-            count: state.count + 1
-        }
-    }
-    if(type === "COUNT_DEC"){
-        return {
-            count: state.count - 1
-        }
-    }
-    return state
-} 
-
-function localStoreReducer (reducer, localStorageKey){
-    function localStoredReducer (state, action){
-        // Если state === undefined, то достать старый state из local storage
-        if(state === undefined){
-            try {
-                return JSON.parse(localStorage[localStorageKey])
-            } catch(e){}
-            
-        }
-       const newState = reducer(state, action)
-        // Сохранить newState в local storage
-        localStorage[localStorageKey] = JSON.stringify(newState)
-       return newState
-
-    } 
-    return localStoredReducer
-}
-
-const store = createStore(localStoreReducer(countReducer, 'count'))
-
-store.subscribe(
-    () => console.log(store.getState())
-)
-store.dispatch({type: "COUNT_INC"})
-store.dispatch({type: "COUNT_INC"})
-store.dispatch({type: "COUNT_DEC"})
-