Browse Source

+ UIContext

ilya_shyian 2 years ago
parent
commit
c1f4781ab7

+ 6 - 3
src/App.js

@@ -6,14 +6,17 @@ import { Router } from 'react-router-dom';
 import { Root } from './components/Root';
 import { Provider } from 'react-redux';
 import { store } from './reducers';
+import { UIContextProvider } from './components/UIContext';
 
 function App() {
     return (
         <Provider store={store}>
             <BrowserRouter>
-                <Box className="App">
-                    <Root />
-                </Box>
+                <UIContextProvider>
+                    <Box className="App">
+                        <Root />
+                    </Box>
+                </UIContextProvider>
             </BrowserRouter>
         </Provider>
     );

+ 1 - 0
src/actions/actionOrderUpdate.js

@@ -1,3 +1,4 @@
+import { actionCartClear, actionPromiseClear } from '../reducers';
 import { actionOrdersAll } from './actionOrdersAll';
 import { actionOrderUpsert } from './actionOrderUpsert';
 

+ 1 - 1
src/actions/actionOrderUpsert.js

@@ -6,7 +6,7 @@ export const actionOrderUpsert = (order) => async (dispatch) => {
     formData.append('orderGoods', JSON.stringify(order.orderGoods));
     formData.append('email', order.email);
     formData.append('phoneNumber', order.phoneNumber);
-    formData.append('adress', order.padress);
+    formData.append('address', order.address);
     formData.append('delivery', order.delivery);
     formData.append('name', order.name);
     formData.append('surname', order.surname);

+ 19 - 21
src/components/CartPage/OrderForm/index.js

@@ -1,10 +1,11 @@
 import { Box, Grid, TextField, MenuItem, Button, Alert, Snackbar } from '@mui/material';
 import * as Yup from 'yup';
 import { useFormik } from 'formik';
-import { connect } from 'react-redux';
-import { actionPromiseClear } from '../../../reducers';
+import { connect, useDispatch } from 'react-redux';
+import { actionCartClear, actionPromiseClear } from '../../../reducers';
 import { actionOrderUpdate } from '../../../actions/actionOrderUpdate';
-import { useEffect, useState } from 'react';
+import { useContext, useEffect, useState } from 'react';
+import { UIContext } from '../../UIContext';
 
 const deliveryOptions = [
     { label: 'Нова пошта', value: 'nova-poshta' },
@@ -28,6 +29,7 @@ const orderSchema = Yup.object().shape({
 });
 
 export const OrderForm = ({ onSubmit = null, promiseStatus = null, serverErrors = [] } = {}) => {
+    const { setAlert } = useContext(UIContext);
     const formik = useFormik({
         initialValues: {
             name: '',
@@ -43,18 +45,27 @@ export const OrderForm = ({ onSubmit = null, promiseStatus = null, serverErrors
             onSubmit(formik.values);
         },
     });
-    const [snackbar, setSnackbar] = useState({ isOpen: false, message: '', type: 'success' });
+    const dispatch = useDispatch();
 
     useEffect(() => {
         if (promiseStatus === 'FULFILLED') {
             formik.setSubmitting(false);
-            setSnackbar({ ...snackbar, isOpen: true, message: 'Готово', type: 'success' });
+            setAlert({
+                show: true,
+                severity: 'success',
+                message: 'Готово',
+            });
+            dispatch(actionPromiseClear('orderUpsert'));
+            dispatch(actionCartClear());
         }
         if (promiseStatus === 'REJECTED') {
             const errorMessage = serverErrors.reduce((prev, curr) => prev + '\n' + curr.message, '');
-            console.log(serverErrors);
+            setAlert({
+                show: true,
+                severity: 'error',
+                message: errorMessage,
+            });
             formik.setSubmitting(false);
-            setSnackbar({ ...snackbar, isOpen: true, message: errorMessage, type: 'error' });
         }
     }, [promiseStatus]);
 
@@ -158,20 +169,7 @@ export const OrderForm = ({ onSubmit = null, promiseStatus = null, serverErrors
                         ))}
                     </TextField>
                 </Grid>
-                <Snackbar
-                    severity={snackbar.type}
-                    message={snackbar.message}
-                    autoHideDuration={3000}
-                    open={snackbar.isOpen}
-                    onClose={() => setSnackbar({ ...snackbar, isOpen: false })}
-                    sx={{
-                        width: 400,
-                    }}
-                >
-                    <Alert severity={snackbar.type} sx={{ width: '100%' }} open={snackbar.isOpen}>
-                        {snackbar.message}
-                    </Alert>
-                </Snackbar>
+
                 <Grid item xs={12} display="flex" justifyContent="flex-end">
                     <Button variant="contained" type="submit" disabled={!formik.isValid || formik.isSubmitting}>
                         Підтвердити

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

@@ -19,7 +19,10 @@ export const CartPage = () => {
             navigate('/');
         }
     }, []);
-    console.log(cart);
+
+    useEffect(() => {
+        !Object.keys(cart).length && navigate('/');
+    }, [cart]);
 
     return (
         <Box className="CartPage">

+ 48 - 0
src/components/UIContext/index.js

@@ -0,0 +1,48 @@
+import { Alert, Snackbar } from '@mui/material';
+import { createContext, useState } from 'react';
+
+export const UIContext = createContext({});
+
+export const UIContextProvider = ({ children }) => {
+    const [alert, setAlert] = useState({
+        show: false,
+        severity: 'info',
+        message: '',
+    });
+
+    const [snackbar, setSnackbar] = useState({
+        show: false,
+        anchorOrigin: { horizontal: 'center', vertical: 'bottom' },
+        message: '',
+    });
+    const handleAlertClose = () =>
+        setAlert({
+            show: false,
+        });
+
+    const handleSnackbarClose = () => {
+        setSnackbar({
+            show: false,
+        });
+    };
+
+    return (
+        <UIContext.Provider value={{ setAlert, setSnackbar }}>
+            {children}
+            <Snackbar open={alert.show} autoHideDuration={4000} onClose={handleAlertClose}>
+                <Alert elevation={6} variant="filled" severity={alert.severity}>
+                    {alert.message}
+                </Alert>
+            </Snackbar>
+            <Snackbar
+                open={snackbar.show}
+                autoHideDuration={4000}
+                onClose={handleSnackbarClose}
+                anchorOrigin={snackbar.anchorOrigin || { horizontal: 'center', vertical: 'bottom' }}
+                message={snackbar.message}
+            >
+                {snackbar.children}
+            </Snackbar>
+        </UIContext.Provider>
+    );
+};

+ 13 - 20
src/components/admin/AdminCategoryPage/CategoryForm.js

@@ -1,10 +1,10 @@
 import { connect } from 'react-redux';
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect, useContext } from 'react';
 import Select from 'react-select';
 import { actionCategoryUpdate } from '../../../actions/actionCategoryUpdate';
 import { actionPromise, actionPromiseClear, store } from '../../../reducers';
 import { Alert, Box, Button, InputLabel, Snackbar, Stack, TextField, Typography } from '@mui/material';
-
+import { UIContext } from '../../UIContext';
 import { useFormik } from 'formik';
 import * as Yup from 'yup';
 import { Error } from '../../common/Error';
@@ -29,7 +29,7 @@ const CategoryForm = ({
     const [inputParent, setInputParent] = useState({});
     const [subCatList, setSubCatList] = useState([]);
     const [parentList, setParentList] = useState([]);
-    const [snackbar, setSnackbar] = useState({ isOpen: false, message: '', type: 'success' });
+    const { setAlert } = useContext(UIContext);
 
     const formik = useFormik({
         initialValues: {
@@ -58,15 +58,22 @@ const CategoryForm = ({
     }, [category]);
 
     useEffect(() => {
-        console.log(promiseStatus);
         if (promiseStatus === 'FULFILLED') {
             formik.setSubmitting(false);
-            setSnackbar({ ...snackbar, isOpen: true, message: 'Готово', type: 'success' });
+            setAlert({
+                show: true,
+                severity: 'success',
+                message: 'Готово',
+            });
         }
         if (promiseStatus === 'REJECTED') {
             const errorMessage = serverErrors.reduce((prev, curr) => prev + '\n' + curr.message, '');
             formik.setSubmitting(false);
-            setSnackbar({ ...snackbar, isOpen: true, message: errorMessage, type: 'error' });
+            setAlert({
+                show: true,
+                severity: 'error',
+                message: errorMessage,
+            });
         }
     }, [promiseStatus]);
 
@@ -149,20 +156,6 @@ const CategoryForm = ({
                     />
                 </Box>
             }
-            <Snackbar
-                severity={snackbar.type}
-                message={snackbar.message}
-                autoHideDuration={3000}
-                open={snackbar.isOpen}
-                onClose={() => setSnackbar({ ...snackbar, isOpen: false })}
-                sx={{
-                    width: 400,
-                }}
-            >
-                <Alert severity={snackbar.type} sx={{ width: '100%' }} open={snackbar.isOpen}>
-                    {snackbar.message}
-                </Alert>
-            </Snackbar>
             <Box direction="row" sx={{ mt: 3 }} justifyContent="flex-end">
                 <Button variant="contained" disabled={!formik.isValid || formik.isSubmitting} type="submit" fullWidth>
                     Зберегти

+ 13 - 19
src/components/admin/AdminGoodPage/GoodForm.js

@@ -1,10 +1,11 @@
 import { connect } from 'react-redux';
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect, useContext } from 'react';
 import { actionPromise, actionPromiseClear } from '../../../reducers';
 import Select from 'react-select';
 import { actionGoodUpdate } from '../../../actions/actionGoodUpdate';
 import { EntityEditor } from '../../common/EntityEditor';
 import { actionUploadFiles } from '../../../actions/actionUploadFiles';
+import { UIContext } from '../../UIContext';
 import {
     Alert,
     Box,
@@ -52,8 +53,7 @@ export const GoodForm = ({
 } = {}) => {
     const [inputCategories, setInputCategories] = useState([]);
     const [inputImages, setInputImages] = useState([]);
-    const [snackbar, setSnackbar] = useState({ isOpen: false, message: '', type: 'success' });
-
+    const { setAlert } = useContext(UIContext);
     const formik = useFormik({
         initialValues: {
             name: '',
@@ -80,12 +80,20 @@ export const GoodForm = ({
     useEffect(() => {
         if (promiseStatus === 'FULFILLED') {
             formik.setSubmitting(false);
-            setSnackbar({ ...snackbar, isOpen: true, message: 'Готово', type: 'success' });
+            setAlert({
+                show: true,
+                severity: 'success',
+                message: 'Готово',
+            });
         }
         if (promiseStatus === 'REJECTED') {
             const errorMessage = serverErrors.reduce((prev, curr) => prev + '\n' + curr.message, '');
             formik.setSubmitting(false);
-            setSnackbar({ ...snackbar, isOpen: true, message: errorMessage, type: 'error' });
+            setAlert({
+                show: true,
+                severity: 'error',
+                message: errorMessage,
+            });
         }
     }, [promiseStatus]);
 
@@ -195,20 +203,6 @@ export const GoodForm = ({
                     Зберегти
                 </Button>
             </Box>
-            <Snackbar
-                severity={snackbar.type}
-                message={snackbar.message}
-                autoHideDuration={3000}
-                open={snackbar.isOpen}
-                onClose={() => setSnackbar({ ...snackbar, isOpen: false })}
-                sx={{
-                    width: 400,
-                }}
-            >
-                <Alert severity={snackbar.type} sx={{ width: '100%' }} open={snackbar.isOpen}>
-                    {snackbar.message}
-                </Alert>
-            </Snackbar>
         </Box>
     );
 };