浏览代码

+orderUpdate

ilya_shyian 2 年之前
父节点
当前提交
e5d28007d8

+ 20 - 8
src/actions/actionCatByIdFull.js

@@ -1,12 +1,24 @@
+import { call, put, take } from "redux-saga/effects";
 import { actionFeedClear, actionPromiseClear } from "../reducers";
 import { actionFeedCategoryGoods } from "../reducers/feedReducer";
+import { promiseWorker } from "../reducers/promiseReducer";
 import { actionCatById } from "./actionCatById";
 
-export const actionCatByIdFull =
-    ({ _id, orderBy }) =>
-    async (dispatch, getState) => {
-        const category = await dispatch(actionCatById({ _id }));
-        dispatch(actionFeedClear());
-        dispatch(actionPromiseClear("feedCategoryGoods"));
-        dispatch(actionFeedCategoryGoods({ category, orderBy, skip: 0 }));
-    };
+export const actionCatByIdFull = ({ _id, orderBy }) => ({ type: "CAT_BY_ID_FULL", payload: { _id, orderBy } });
+
+export function* catByIdFullWorker(action) {
+    const { _id, orderBy = "createdAt" } = action.payload || {};
+
+    const category = yield call(promiseWorker, actionCatById({ _id }));
+
+    yield put(actionFeedClear());
+    yield put(actionPromiseClear("feedCategoryGoods"));
+    console.log(category);
+    yield put(actionFeedCategoryGoods({ category, orderBy, skip: 0 }));
+
+    yield take("CAT_BY_ID_FULL_CLEAR");
+
+    yield put(actionPromiseClear("catById"));
+    yield put(actionFeedClear());
+    yield put(actionPromiseClear("feedCategoryGoods"));
+}

+ 0 - 8
src/actions/actionCatByIdFullClear.js

@@ -1,8 +0,0 @@
-import { actionFeedClear, actionPromiseClear } from "../reducers";
-import { actionCatById } from "./actionCatById";
-
-export const actionCatByIdFullClear = () => async (dispatch, getState) => {
-    dispatch(actionPromiseClear("catById"));
-    dispatch(actionFeedClear());
-    dispatch(actionPromiseClear("feedCategoryGoods"));
-};

+ 33 - 26
src/actions/actionCategoryGoods.js

@@ -1,17 +1,24 @@
+import { call, cancelled, select } from "redux-saga/effects";
 import { gql } from "../helpers";
 import { actionPromise } from "../reducers";
+import { promiseWorker } from "../reducers/promiseReducer";
 
-export const actionCategoryGoods =
-    ({ limit = 20, skip = 0, promiseName = "categoryGoods", orderBy = "_id", category } = {}) =>
-    async (dispatch, getState) => {
-        if (!category) {
-            return;
-        }
-        dispatch(
-            actionPromise(
-                promiseName,
-                gql(
-                    `query GCategoryGoods($query:String){
+export const actionCategoryGoods = ({ limit = 20, skip = 0, promiseName = "categoryGoods", orderBy = "_id", category } = {}) => ({
+    type: "CATEGORY_GOODS",
+    payload: { limit, skip, promiseName, orderBy, category },
+});
+export function* categoryGoodsWorker(action) {
+    const { limit = 20, skip = 0, promiseName = "categoryGoods", orderBy = "_id", category } = action.payload || {};
+    if (!category) {
+        return;
+    }
+
+    yield call(
+        promiseWorker,
+        actionPromise(
+            promiseName,
+            gql(
+                `query CategoryGoods($query:String){
                         GoodFind(query: $query){
                             _id name price images{
                                 _id url
@@ -22,19 +29,19 @@ export const actionCategoryGoods =
                             amount
                         }
                     }`,
-                    {
-                        query: JSON.stringify([
-                            {
-                                categories__in: [category._id],
-                            },
-                            {
-                                limit: !!limit ? limit : 100,
-                                skip: skip,
-                                orderBy,
-                            },
-                        ]),
-                    }
-                )
+                {
+                    query: JSON.stringify([
+                        {
+                            categories__in: [category._id],
+                        },
+                        {
+                            limit: !!limit ? limit : 100,
+                            skip: skip,
+                            orderBy,
+                        },
+                    ]),
+                }
             )
-        );
-    };
+        )
+    );
+}

+ 19 - 4
src/actions/actionOrderUpdate.js

@@ -1,7 +1,22 @@
+import { call, put, select } from "redux-saga/effects";
+import { actionCartClear } from "../reducers";
+import { promiseWorker } from "../reducers/promiseReducer";
 import { actionOrdersAll } from "./actionOrdersAll";
 import { actionOrderUpsert } from "./actionOrderUpsert";
+export const actionOrderUpdate = (order) => ({ type: "ORDER_UPDATE", payload: order });
+export function* orderUpdateWorker(action) {
+    const order = action.payload || {};
+    if (!order?.orderGoods?.length) {
+        return;
+    }
+    yield call(promiseWorker, actionOrderUpsert(order));
+    yield put(actionOrdersAll());
 
-export const actionOrderUpdate = (order) => async (dispatch, getState) => {
-    await dispatch(actionOrderUpsert(order));
-    await dispatch(actionOrdersAll());
-};
+    const {
+        promise: { orderUpsert },
+    } = yield select();
+
+    if (orderUpsert.status === "FULFILLED") {
+        yield put(actionCartClear());
+    }
+}

+ 8 - 22
src/actions/actionOrderUpsert.js

@@ -1,32 +1,18 @@
 import { gql } from "../helpers";
 import { actionCartClear, actionPromise } from "../reducers";
 
-export const actionOrderUpsert = (order) => async (dispatch, getState) => {
-    if (!order?.orderGoods?.length) {
-        return;
-    }
-    await dispatch(
-        actionPromise(
-            "orderUpsert",
-            gql(
-                `mutation newOrder($order:OrderInput!){
+export const actionOrderUpsert = (order) =>
+    actionPromise(
+        "orderUpsert",
+        gql(
+            `mutation newOrder($order:OrderInput!){
                   OrderUpsert(order:$order){
                     _id price
                   }
                 }
             `,
-                {
-                    order,
-                }
-            )
+            {
+                order,
+            }
         )
     );
-    let {
-        promise: { orderUpsert },
-    } = getState();
-
-    if (orderUpsert.status === "FULFILLED") {
-        dispatch(actionCartClear());
-        // dispatch(actionOrders(token));
-    }
-};

+ 18 - 23
src/actions/actionOrdersAll.js

@@ -1,14 +1,11 @@
 import { actionPromise } from "../reducers";
 import { gql } from "../helpers";
 
-export const actionOrdersAll =
-    ({ limit = 0, skip = 0, promiseName = "adminOrdersAll", orderBy = "_id", status = 0 } = {}) =>
-    async (dispatch, getState) => {
-        dispatch(
-            actionPromise(
-                promiseName,
-                gql(
-                    `query OrdersAll($query:String){
+export const actionOrdersAll = ({ limit = 0, skip = 0, promiseName = "adminOrdersAll", orderBy = "_id", status = 0 } = {}) =>
+    actionPromise(
+        promiseName,
+        gql(
+            `query OrdersAll($query:String){
                         OrderFind(query: $query){
                             _id status price 
                             owner{
@@ -21,19 +18,17 @@ export const actionOrdersAll =
                             }
                         }
                     }`,
+            {
+                query: JSON.stringify([
                     {
-                        query: JSON.stringify([
-                            {
-                                status,
-                            },
-                            {
-                                limit: !!limit ? limit : 100,
-                                skip: skip,
-                                orderBy,
-                            },
-                        ]),
-                    }
-                )
-            )
-        );
-    };
+                        status,
+                    },
+                    {
+                        limit: !!limit ? limit : 100,
+                        skip: skip,
+                        orderBy,
+                    },
+                ]),
+            }
+        )
+    );

+ 1 - 2
src/actions/actionPageStart.js

@@ -3,8 +3,7 @@ import { actionCatAll } from "./actionCatAll";
 import { actionGoodsPopular } from "./actionGoodsPopular";
 import { actionOrders } from "./actionOrders";
 import { actionRootCats } from "./actionRootCats";
-import { put, select, call } from "redux-saga/effects";
-import { promiseWorker } from "../reducers/promiseReducer";
+import { put, select } from "redux-saga/effects";
 
 export const actionPageStart = () => ({ type: "PAGE_START" });
 

+ 13 - 4
src/components/CartPage/index.js

@@ -1,6 +1,6 @@
 import { Box, Button, Stack, Table, TableBody, TableCell, TableRow, Typography } from "@mui/material";
 import { useFormik } from "formik";
-import { useContext, useEffect } from "react";
+import { useContext, useEffect, useState } from "react";
 import { connect, useDispatch, useSelector } from "react-redux";
 import { useNavigate } from "react-router-dom";
 import { actionOrderUpdate } from "../../actions/actionOrderUpdate";
@@ -8,16 +8,17 @@ import { actionCartDelete } from "../../reducers";
 import { UIContext } from "../UIContext";
 import { CartItem } from "./CartItem";
 
-export const CartPage = ({ onConfirm, promiseStatus, serverErrors }) => {
+export const CartPage = ({ onConfirm, promiseStatus, serverErrors, onDeleteClick }) => {
     const cart = useSelector((state) => state.cart || {});
     const { setAlert } = useContext(UIContext);
     const sum = Object.entries(cart).reduce((prev, [_id, order]) => prev + order.count * order.good.price, 0);
-    const dispatch = useDispatch();
+    const [promiseTimeOut, setPromiseTimeOut] = useState(null);
     const navigate = useNavigate();
 
     const formik = useFormik({
         initialValues: {},
         onSubmit: () => {
+            setPromiseTimeOut(setTimeout(() => formik.setSubmitting(false), 3000));
             onConfirm && Object.keys(cart).length && onConfirm({ orderGoods: Object.values(cart) });
         },
     });
@@ -26,6 +27,9 @@ export const CartPage = ({ onConfirm, promiseStatus, serverErrors }) => {
         if (!Object.entries(cart).length) {
             navigate("/");
         }
+        return () => {
+            promiseTimeOut && clearTimeout(promiseTimeOut);
+        };
     }, []);
 
     useEffect(() => {
@@ -35,6 +39,8 @@ export const CartPage = ({ onConfirm, promiseStatus, serverErrors }) => {
     useEffect(() => {
         if (promiseStatus === "FULFILLED") {
             formik.setSubmitting(false);
+            promiseTimeOut && clearTimeout(promiseTimeOut);
+            setPromiseTimeOut(null);
             setAlert({
                 show: true,
                 severity: "success",
@@ -44,6 +50,8 @@ export const CartPage = ({ onConfirm, promiseStatus, serverErrors }) => {
         if (promiseStatus === "REJECTED") {
             const errorMessage = serverErrors.reduce((prev, curr) => prev + "\n" + curr.message, "");
             formik.setSubmitting(false);
+            promiseTimeOut && clearTimeout(promiseTimeOut);
+            setPromiseTimeOut(null);
             setAlert({
                 show: true,
                 severity: "error",
@@ -59,7 +67,7 @@ export const CartPage = ({ onConfirm, promiseStatus, serverErrors }) => {
                 <Table className="table">
                     <TableBody>
                         {Object.entries(cart).map(([_id, order]) => (
-                            <CartItem order={order} onDeleteClick={(good) => dispatch(actionCartDelete(good))} key={_id} />
+                            <CartItem order={order} onDeleteClick={(good) => onDeleteClick(good)} key={_id} />
                         ))}
 
                         <TableRow>
@@ -96,5 +104,6 @@ export const CCartPage = connect(
     }),
     {
         onConfirm: (order) => actionOrderUpdate(order),
+        onDeleteClick: (good) => actionCartDelete(good),
     }
 )(CartPage);

+ 2 - 4
src/components/LayoutPage/GoodsPageContainer.js

@@ -1,9 +1,7 @@
 import { connect } from "react-redux";
 import { useEffect } from "react";
-import { useDispatch } from "react-redux";
 import { useParams, useSearchParams } from "react-router-dom";
 import { actionCatByIdFull } from "../../actions/actionCatByIdFull";
-import { actionCatByIdFullClear } from "../../actions/actionCatByIdFullClear";
 import { actionFeedCategoryGoods } from "../../reducers/feedReducer";
 import { InfScroll } from "../common/InfScroll";
 import { CGoodsPage } from "../GoodsPage";
@@ -17,7 +15,7 @@ const GoodsPageContainer = ({ feed, goods, promiseStatus, onLoad, onUnmount, onS
         onLoad({ orderBy, _id: params._id });
 
         return () => {
-            onUnmount();
+            onUnmount && onUnmount();
         };
     }, [params._id, orderBy]);
 
@@ -40,7 +38,7 @@ export const CAdminGoodsPageContainer = connect(
         promiseStatus: state.promise?.feedCategoryGoods?.status || null,
     }),
     {
-        onUnmount: () => actionCatByIdFullClear(),
+        onUnmount: () => ({ type: "CAT_BY_ID_FULL_CLEAR" }),
         onLoad: ({ orderBy, _id }) => actionCatByIdFull({ orderBy, _id }),
         onScroll: ({ feed, orderBy, category }) => actionFeedCategoryGoods({ skip: feed.length || 0, orderBy, category }),
     }

+ 10 - 10
src/components/LayoutPage/index.js

@@ -46,19 +46,19 @@ const CDashboardPageContainer = connect(null, {
 
 const CGoodsList = connect((state) => ({ goods: state.promise?.pageGoodsFind?.payload || [] }))(GoodList);
 
-const GoodsListContainer = ({ onLoad }) => {
-    const params = useParams();
+// const GoodsListContainer = ({ onLoad }) => {
+//     const params = useParams();
 
-    useEffect(() => {
-        onLoad({ text: params.searchData, promiseName: "pageGoodsFind" });
-    }, [params.searchData]);
+//     useEffect(() => {
+//         onLoad({ text: params.searchData, promiseName: "pageGoodsFind" });
+//     }, [params.searchData]);
 
-    return <CGoodsList />;
-};
+//     return <CGoodsList />;
+// };
 
-const CGoodsListContainer = connect(null, {
-    onLoad: ({ text, promiseName }) => actionOrders({ text, promiseName }),
-})(GoodsListContainer);
+// const CGoodsListContainer = connect(null, {
+//     onLoad: ({ text, promiseName }) => actionOrders({ text, promiseName }),
+// })(GoodsListContainer);
 
 const MainPageContainer = ({ onLoad, goods }) => {
     useEffect(() => {

+ 2 - 1
src/components/admin/AdminGoodPage/GoodForm.js

@@ -36,6 +36,7 @@ export const GoodForm = ({
     onSave,
     onClose,
     onDelete,
+
     promiseStatus,
     deletePromiseStatus,
     catList = [],
@@ -120,7 +121,7 @@ export const GoodForm = ({
             });
         }
         return () => {
-            dispatch(actionPromiseClear("goodDelete"));
+            
         };
     }, [deletePromiseStatus]);
 

+ 15 - 5
src/reducers/feedReducer.js

@@ -7,6 +7,7 @@ import { actionOrdersFind } from "../actions/actionOrdersFind";
 import { actionCategoryGoods } from "../actions/actionCategoryGoods";
 import { actionUsersFind } from "../actions/actionUsersFind";
 import { actionUsersAll } from "../actions/actionUsersAll";
+import { put, takeLatest } from "redux-saga/effects";
 
 function feedReducer(state = { payload: [] }, { type, payload = [] }) {
     if (type === "FEED_ADD") {
@@ -30,11 +31,16 @@ const actionFeedGoods =
         await dispatch(actionGoodsAll({ skip, limit: 1, promiseName: "feedGoodsAll", orderBy }));
     };
 
-const actionFeedCategoryGoods =
-    ({ skip = 0, orderBy = "_id", category }) =>
-    async (dispatch, getState) => {
-        await dispatch(actionCategoryGoods({ skip, limit: 1, promiseName: "feedCategoryGoods", orderBy, category }));
-    };
+const actionFeedCategoryGoods = ({ skip = 0, orderBy = "_id", category } = {}) => ({
+    type: "FEED_CATEGORY_GOODS",
+    payload: { skip, orderBy, category },
+});
+
+function* feedCategoryGoodsWorker(action) {
+    const { skip = 0, orderBy = "_id", category } = action.payload || {};
+
+    yield put(actionCategoryGoods({ skip, limit: 1, promiseName: "feedCategoryGoods", orderBy, category }));
+}
 
 const actionFeedGoodsFind =
     ({ skip = 0, text = "", orderBy = "_id" }) =>
@@ -92,3 +98,7 @@ export {
     actionFeedUsers,
     actionFeedUsersFind,
 };
+
+export function* feedWatcher() {
+    yield takeLatest("FEED_CATEGORY_GOODS", feedCategoryGoodsWorker);
+}

+ 2 - 1
src/reducers/index.js

@@ -25,6 +25,7 @@ import {
     feedReducer,
     actionFeedUsers,
     actionFeedUsersFind,
+    feedWatcher,
 } from "./feedReducer";
 
 export { cartReducer, actionCartAdd, actionCartChange, actionCartDelete, actionCartClear };
@@ -56,7 +57,7 @@ export const store = createStore(
 );
 
 function* rootSaga() {
-    yield all([promiseWatcher()]);
+    yield all([promiseWatcher(), feedWatcher()]);
 }
 
 sagaMiddleware.run(rootSaga);

+ 9 - 3
src/reducers/promiseReducer.js

@@ -1,5 +1,8 @@
-import { put, takeEvery } from "redux-saga/effects";
+import { put, takeEvery, takeLatest } from "redux-saga/effects";
 import { aboutMeWorker } from "../actions/actionAboutMe";
+import { catByIdFullWorker } from "../actions/actionCatByIdFull";
+import { categoryGoodsWorker } from "../actions/actionCategoryGoods";
+import { orderUpdateWorker } from "../actions/actionOrderUpdate";
 import { pageStartWorker } from "../actions/actionPageStart";
 
 export function promiseReducer(state = {}, { type, name, status, payload, error }) {
@@ -37,6 +40,9 @@ export function* promiseWorker(action) {
 
 export function* promiseWatcher() {
     yield takeEvery("PROMISE_START", promiseWorker);
-    yield takeEvery("PAGE_START", pageStartWorker);
-    yield takeEvery("ABOUT_ME", aboutMeWorker);
+    yield takeLatest("PAGE_START", pageStartWorker);
+    yield takeLatest("ABOUT_ME", aboutMeWorker);
+    yield takeLatest("CAT_BY_ID_FULL", catByIdFullWorker);
+    yield takeLatest("CATEGORY_GOODS", categoryGoodsWorker);
+    yield takeLatest("ORDER_UPDATE", orderUpdateWorker);
 }