Selaa lähdekoodia

editForm instead of editGood and editCategory

viktoriia.kapran 1 vuosi sitten
vanhempi
commit
83961e989f

+ 1 - 1
js21 react/my-react-app/src/components/Dnd.js

@@ -7,7 +7,7 @@ import {
   useSensor,
   useSensors, useDroppable
 } from "@dnd-kit/core";
-import { sortableKeyboardCoordinates, rectSortingStrategy, SortableContext, useSortable, horizontalListSortingStrategy } from "@dnd-kit/sortable";
+import { sortableKeyboardCoordinates, rectSortingStrategy, SortableContext, useSortable } from "@dnd-kit/sortable";
 import { CSS } from "@dnd-kit/utilities";
 import { arrayMoveImmutable } from 'array-move';
 

+ 0 - 88
js21 react/my-react-app/src/components/EditCategory.js

@@ -1,88 +0,0 @@
-import { Box, Button, Checkbox, FormControl, InputLabel, ListItemText, MenuItem, OutlinedInput, Select, Stack, TextField } from '@mui/material';
-import React, { useState } from 'react';
-import { useNavigate } from 'react-router-dom';
-import { useCreateCategoryMutation, useGetCategoriesQuery, useGetCategoriesWithSubCategoriesQuery } from '../store/api';
-
-const ITEM_HEIGHT = 48;
-const ITEM_PADDING_TOP = 8;
-const MenuProps = {
-  PaperProps: {
-    style: {
-      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
-      width: 250,
-    },
-  },
-};
-
-function EditCategory({ buttonText, nameCategory, subCategories, categoryId }) {
-  const { data } = useGetCategoriesWithSubCategoriesQuery();
-  const [name, setName] = useState(nameCategory || '');
-  const [selectedCategories, setSelectedCategories] = useState(subCategories || []);
-  const [createCategory, result] = useCreateCategoryMutation();
-
-  const navigate = useNavigate();
-
-  const onSubcategoryClick = (category) => {
-    if (selectedCategories.find(selectedCategory => selectedCategory._id == category._id)) {
-      setSelectedCategories(selectedCategories.filter(selectedCategory => selectedCategory._id != category._id));
-    } else {
-      setSelectedCategories([...selectedCategories, category]);
-    }
-  };
-//
-
-
-  const handleSubmit = () => {
-    const category = {
-      name,
-      parent: null,
-      subCategories: selectedCategories.map(subCategory => ({
-                                                              _id: subCategory._id,
-                                                              name: subCategory.name,
-                                                              
-                                                            })),
-    }
-    if (categoryId) {
-      category._id = categoryId;
-    }
-    console.log(category);
-    createCategory(category).then(response => {
-      navigate('/admin/categories');
-    });
-
-  }
-
-  return (
-    <Box component='form' onSubmit={handleSubmit}>
-      <Stack >
-        <TextField
-          sx={{ m: '0 auto 20px', width: '100%' }}
-          value={name}
-          onChange={(e) => setName(e.target.value)}
-          label='Category name'
-        />
-        <FormControl
-          sx={{ m: '0 auto 20px', width: '100%' }}>
-          <InputLabel>Subcategories</InputLabel>
-          <Select
-            multiple
-            value={selectedCategories}
-            input={<OutlinedInput label="Category name" />}
-            renderValue={(selected) => selected.map(item => item.name).join(', ')}
-            MenuProps={MenuProps}
-          >
-            {data?.CategoryFind?.map((category) => (
-              <MenuItem key={category._id} value={category} onClick={() => onSubcategoryClick(category)}>
-                <Checkbox checked={!!selectedCategories?.find(selectedCategory => selectedCategory._id === category._id)} />
-                <ListItemText primary={category.name} />
-              </MenuItem>
-            ))}
-          </Select>
-        </FormControl>
-        <Button variant="contained" sx={{ maxWidth: '200px', width: '100%', mx: 'auto' }} onClick={() => handleSubmit()}>{buttonText}</Button>
-      </Stack>
-    </Box>
-  )
-}
-
-export default EditCategory;

+ 140 - 0
js21 react/my-react-app/src/components/EditForm.js

@@ -0,0 +1,140 @@
+import { Box, Button, Checkbox, FormControl, InputLabel, ListItemText, MenuItem, OutlinedInput, Select, Stack, TextField } from '@mui/material';
+import React, { useState } from 'react';
+import { useLocation, useNavigate } from 'react-router-dom';
+import ImageUploader from '../components/ImageUploader';
+import { useCreateCategoryMutation, useCreateGoodMutation, useGetCategoriesWithSubCategoriesQuery } from '../store/api';
+
+
+const ITEM_HEIGHT = 48;
+const ITEM_PADDING_TOP = 8;
+const MenuProps = {
+  PaperProps: {
+    style: {
+      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
+      width: 250,
+    },
+  },
+};
+
+function EditForm({ id, name, categories, price, description, goodImages, buttonText }) {
+  const { data } = useGetCategoriesWithSubCategoriesQuery();
+  const [itemName, setItemName] = useState(name || '');
+  const [selectedCategories, setSelectedCategories] = useState(categories || []);
+  const [itemPrice, setItemPrice] = useState(price || 0);
+  const [itemDescription, setItemDescription] = useState(description || '');
+  const [images, setImages] = useState(goodImages || []);
+  const navigate = useNavigate();
+  const location = useLocation();
+  const goodLocation = location.pathname == '/admin/good' || location.pathname == `/admin/good/${id}`;
+  const categoryLocation = location.pathname == '/admin/category' || location.pathname == `/admin/category/${id}`
+
+  const [createGood, result] = useCreateGoodMutation();
+
+  const [createCategory, resultMut] = useCreateCategoryMutation();
+
+
+  const onCategoryClick = (category) => {
+    if (selectedCategories.find(selectedCategory => selectedCategory._id == category._id)) {
+      setSelectedCategories(selectedCategories.filter(selectedCategory => selectedCategory._id != category._id));
+    } else {
+      setSelectedCategories([...selectedCategories, category]);
+    }
+  };
+  const handlePriceChange = (event) => {
+    setItemPrice(event.target.value);
+  };
+  const handleDescriptionChange = (event) => {
+    setItemDescription(event.target.value);
+  }
+
+
+  const handleSubmit = () => {
+
+    const item = {
+      name: itemName,
+    };
+    if (goodLocation) {
+      item.categories = selectedCategories.map(category => ({
+        _id: category._id,
+        name: category.name
+      }));
+      item.price = +itemPrice;
+      item.description = itemDescription;
+      item.images = images.map(image => ({ _id: image._id }));
+    }
+    if (categoryLocation) {
+      item.subCategories = selectedCategories.map(subCategory => ({
+        _id: subCategory._id,
+        name: subCategory.name,
+        
+      }));
+    }
+    if (id) {
+      item._id = id;
+    }
+    if (goodLocation) {
+      createGood(item).then(response => {
+        navigate('/admin/goods');
+      });
+    } else if (categoryLocation) {
+      createCategory(item).then(response => {
+        navigate('/admin/categories');
+      });
+    }
+
+  }
+
+  return (
+    <Box component='form' onSubmit={handleSubmit}>
+      <Stack>
+        <TextField
+          sx={{ m: '0 auto 20px', width: '100%' }}
+          value={itemName}
+          onChange={(e) => setItemName(e.target.value)}
+          label='Name'
+        />
+        <FormControl
+          sx={{ m: '0 auto 20px', width: '100%' }}>
+          <InputLabel>{goodLocation ? 'Category' : 'Subcategories'}</InputLabel>
+          <Select
+            multiple
+            value={selectedCategories}
+            input={<OutlinedInput label={goodLocation ? 'Category' : 'Subcategories'} />}
+            renderValue={(selected) => selected.map(item => item.name).join(', ')}
+            MenuProps={MenuProps}
+          >
+            {data?.CategoryFind?.map((category) => (
+              <MenuItem key={category._id} value={category} onClick={() => onCategoryClick(category)}>
+                <Checkbox checked={!!selectedCategories?.find(selectedCategory => selectedCategory._id === category._id)} />
+                <ListItemText primary={category.name} />
+              </MenuItem>
+            ))}
+          </Select>
+        </FormControl>
+        {goodLocation &&
+          <>
+            <TextField
+              sx={{ m: '0 auto 20px', width: '100%' }}
+              type='number'
+              label='Price'
+              value={itemPrice}
+              onChange={handlePriceChange}
+            />
+            <TextField
+              sx={{ m: '0 auto 20px', width: '100%' }}
+              label="Description"
+              multiline
+              rows={4}
+              value={itemDescription}
+              onChange={handleDescriptionChange}
+            />
+            <ImageUploader passImages={goodImages} onChange={(images) => setImages(images)} />
+          </>
+        }
+        <Button variant="contained" sx={{ maxWidth: '200px', width: '100%', m: '20px auto 0' }} onClick={() => handleSubmit()}>{buttonText}</Button>
+      </Stack>
+    </Box>
+  )
+}
+
+export default EditForm;

+ 0 - 116
js21 react/my-react-app/src/components/EditGood.js

@@ -1,116 +0,0 @@
-import { Box, Button, Checkbox, FormControl, InputLabel, ListItemText, MenuItem, OutlinedInput, Select, Stack, TextField } from '@mui/material';
-import React, { useState } from 'react';
-import { useNavigate } from 'react-router-dom';
-import ImageUploader from '../components/ImageUploader';
-import { useCreateGoodMutation, useGetCategoriesWithSubCategoriesQuery } from '../store/api';
-
-
-const ITEM_HEIGHT = 48;
-const ITEM_PADDING_TOP = 8;
-const MenuProps = {
-  PaperProps: {
-    style: {
-      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
-      width: 250,
-    },
-  },
-};
-
-function EditGood({ name, categories, price, description, goodImages, goodId, buttonText }) {
-  const { data } = useGetCategoriesWithSubCategoriesQuery();
-  const [goodName, setGoodName] = useState(name || '');
-  const [selectedCategories, setSelectedCategories] = useState(categories || []);
-  const [goodPrice, setGoodPrice] = useState(price || 0);
-  const [goodDescription, setGoodDescription] = useState(description || '');
-  const [images, setImages] = useState(goodImages || []);
-  const navigate = useNavigate();
-  const [createGood, result] = useCreateGoodMutation();
-
-
-  const onCategoryClick = (category) => {
-    if (selectedCategories.find(selectedCategory => selectedCategory._id == category._id)) {
-      setSelectedCategories(selectedCategories.filter(selectedCategory => selectedCategory._id != category._id));
-    } else {
-      setSelectedCategories([...selectedCategories, category]);
-    }
-  };
-  const handlePriceChange = (event) => {
-    setGoodPrice(event.target.value);
-  };
-  const handleDescriptionChange = (event) => {
-    setGoodDescription(event.target.value);
-  }
-
-
-  const handleSubmit = () => {
-
-    const good = {
-      name: goodName,
-      categories: selectedCategories.map(category => ({
-        _id: category._id,
-        name: category.name
-      })),
-      price: +goodPrice,
-      description: goodDescription,
-      images: images.map(image => ({ _id: image._id }))
-    };
-    if (goodId) {
-      good._id = goodId;
-    }
-    createGood(good).then(response => {
-      navigate('/admin/goods');
-    });
-  }
-
-
-  return (
-    <Box component='form' onSubmit={handleSubmit}>
-      <Stack>
-        <TextField
-          sx={{ m: '0 auto 20px', width: '100%' }}
-          value={goodName}
-          onChange={(e) => setGoodName(e.target.value)}
-          label='Good name'
-        />
-        <FormControl
-          sx={{ m: '0 auto 20px', width: '100%' }}>
-          <InputLabel>Category</InputLabel>
-          <Select
-            multiple
-            value={selectedCategories}
-            input={<OutlinedInput label="Category name" />}
-            renderValue={(selected) => selected.map(item => item.name).join(', ')}
-            MenuProps={MenuProps}
-          >
-            {data?.CategoryFind?.map((category) => (
-              <MenuItem key={category._id} value={category} onClick={() => onCategoryClick(category)}>
-                <Checkbox checked={!!selectedCategories?.find(selectedCategory => selectedCategory._id === category._id)} />
-                <ListItemText primary={category.name} />
-              </MenuItem>
-            ))}
-          </Select>
-        </FormControl>
-        <TextField
-          sx={{ m: '0 auto 20px', width: '100%' }}
-          type='number'
-          label='Price'
-          value={goodPrice}
-          onChange={handlePriceChange}
-        />
-        <TextField
-          sx={{ m: '0 auto 20px', width: '100%' }}
-          label="Description"
-          multiline
-          rows={4}
-          value={goodDescription}
-          onChange={handleDescriptionChange}
-        />
-        <ImageUploader passImages={goodImages} onChange={(images) => setImages(images)} />
-
-        <Button variant="contained" sx={{ maxWidth: '200px', width: '100%', m: '20px auto 0' }} onClick={() => handleSubmit()}>{buttonText}</Button>
-      </Stack>
-    </Box>
-  )
-}
-
-export default EditGood;

+ 2 - 4
js21 react/my-react-app/src/components/ImageUploader.js

@@ -1,11 +1,9 @@
-import React, { useCallback, useMemo, useState } from 'react';
-import { imageApi, useUploadImageMutation } from '../store/api';
+import React, { useMemo, useState } from 'react';
+import {  useUploadImageMutation } from '../store/api';
 import { useDropzone } from 'react-dropzone';
 import { Image } from './Image/Image';
 import { Box } from '@mui/material';
 import Dnd from './Dnd';
-import { useSelector } from 'react-redux';
-
 
 const baseStyle = {
   flex: 1,

+ 1 - 1
js21 react/my-react-app/src/components/Layout.js

@@ -1,5 +1,5 @@
 import React from 'react';
-import { Link, Outlet } from 'react-router-dom';
+import { Outlet } from 'react-router-dom';
 import Footer from './Footer';
 import Header from './Header';
 import CategoryMenu from './CategoriesMenu/CategoryMenu';

+ 1 - 1
js21 react/my-react-app/src/components/LoginForm.js

@@ -4,7 +4,7 @@ import OutlinedInput from '@mui/material/OutlinedInput';
 import IconButton from '@mui/material/IconButton';
 import Visibility from '@mui/icons-material/Visibility';
 import VisibilityOff from '@mui/icons-material/VisibilityOff';
-import { FormControl, Button, Box, Stack, Alert } from '@mui/material';
+import { FormControl, Button, Box, Stack } from '@mui/material';
 import { useLocation } from 'react-router-dom';
 
 const LoginForm = ({ submit, onSubmit }) => {

+ 1 - 2
js21 react/my-react-app/src/pages/CartPage.js

@@ -1,4 +1,4 @@
-import React, { useState } from 'react';
+import React from 'react';
 import Title from '../components/Title';
 import { clearCart } from '../store/cartSlice';
 import CartGood from '../components/CartGood';
@@ -13,7 +13,6 @@ export default function CartPage() {
   const token = useSelector(state => state.auth.token);
   const [createOrderAction, result] = useCreateOrderMutation();
   const dispatch = useDispatch();
-  console.log(goods);
   const createOrder = (orderGoods) => {
     const orderGoodsDto = [];
     orderGoods.forEach(orderGood => {

+ 1 - 1
js21 react/my-react-app/src/pages/LoginPage.js

@@ -1,4 +1,4 @@
-import { Box, Stack } from '@mui/material';
+import { Box } from '@mui/material';
 import React, { useEffect } from 'react';
 import { useDispatch, useSelector } from 'react-redux';
 import LoginForm from '../components/LoginForm';

+ 0 - 1
js21 react/my-react-app/src/pages/RegisterPage.js

@@ -19,7 +19,6 @@ export default function RegisterPage() {
       navigate('/');
     }
   }, [token]);
-console.log(isError)
   const onRegister = (login, password) => {
 
     fullRegister({ login, password }).then(res => {

+ 0 - 1
js21 react/my-react-app/src/pages/admin/AdminPage.js

@@ -1,5 +1,4 @@
 import React from 'react';
-import { useGetGoodsQuery, useGetOrderGoodQuery, useGetOwnerOrderQuery, useGetUsersQuery } from '../../store/api';
 
 export default function AdminPage() {
   return (

+ 1 - 1
js21 react/my-react-app/src/pages/admin/CategoriesPage.js

@@ -2,7 +2,7 @@ import React, { useState } from 'react';
 import { useDeleteCategoryMutation, useGetCategoriesWithSubCategoriesQuery, useGetCategoryCountQuery } from '../../store/api';
 import Loader from '../../components/Loader';
 import {
-  Button, IconButton, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Tooltip, Dialog,
+  Button, IconButton, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Dialog,
   DialogActions, DialogContent, DialogContentText, TablePagination, Collapse
 } from '@mui/material';
 import { DeleteOutlineOutlined, Edit, KeyboardArrowDown, KeyboardArrowUp } from '@mui/icons-material';

+ 2 - 2
js21 react/my-react-app/src/pages/admin/CreateCategoryPage.js

@@ -1,6 +1,6 @@
 import { Box } from '@mui/material';
 import React from 'react';
-import EditCategory from '../../components/EditCategory';
+import EditForm from '../../components/EditForm';
 import Title from '../../components/Title';
 
 
@@ -10,7 +10,7 @@ function CreateCategoryPage() {
   return (
     <Box sx={{ maxWidth: '450px', m: '20px auto', width: '100%' }} >
       <Title>Create category</Title>
-      <EditCategory buttonText='Add category' />
+      <EditForm buttonText='Add category' />
     </Box >
 
   )

+ 2 - 2
js21 react/my-react-app/src/pages/admin/CreateGoodPage.js

@@ -1,13 +1,13 @@
 import { Box } from '@mui/material';
 import React from 'react';
-import EditGood from '../../components/EditGood';
+import EditForm from '../../components/EditForm';
 import Title from '../../components/Title';
 
 const CreateGoodPage = () => {
   return (
     <Box sx={{ maxWidth: '450px', m: '20px auto', width: '100%' }} >
       <Title>Create good</Title>
-      <EditGood buttonText='Add' />
+      <EditForm buttonText='Add'/>
     </Box >
   )
 }

+ 5 - 5
js21 react/my-react-app/src/pages/admin/EditCategoryPage.js

@@ -2,9 +2,9 @@ import { Box } from '@mui/system';
 import React from 'react';
 import { useParams } from 'react-router-dom';
 import { useGetCategoryByIdQuery } from '../../store/api';
-import EditCategory from '../../components/EditCategory';
 import Loader from '../../components/Loader';
 import Title from '../../components/Title';
+import EditForm from '../../components/EditForm';
 
 function EditCategoryPage() {
   const { categoryId } = useParams();
@@ -14,11 +14,11 @@ function EditCategoryPage() {
       {isFetching ? <Loader /> :
         <Box sx={{ maxWidth: '450px', m: '20px auto', width: '100%' }}>
           <Title>Edit category</Title>
-          <EditCategory
+          <EditForm
             buttonText='Update'
-            categoryId={categoryId}
-            nameCategory={data?.CategoryFindOne?.name}
-            subCategories={data?.CategoryFindOne?.subCategories}
+            id={categoryId}
+            name={data?.CategoryFindOne?.name}
+            categories={data?.CategoryFindOne?.subCategories}
           />
         </Box>
       }

+ 3 - 3
js21 react/my-react-app/src/pages/admin/EditGoodPage.js

@@ -1,10 +1,10 @@
 import { Box } from '@mui/material';
 import React from 'react';
 import { useParams } from 'react-router-dom';
-import EditGood from '../../components/EditGood';
 import Title from '../../components/Title';
 import { useGetGoodByIdQuery } from '../../store/api';
 import Loader from '../../components/Loader';
+import EditForm from '../../components/EditForm';
 
 function EditGoodPage() {
   const { goodId } = useParams();
@@ -14,9 +14,9 @@ function EditGoodPage() {
       {isFetching ? <Loader /> :
         <Box sx={{ maxWidth: '450px', m: '20px auto', width: '100%' }} >
           <Title>Create good</Title>
-          <EditGood
+          <EditForm
             buttonText='Edit'
-            goodId={goodId}
+            id={goodId}
             name={data?.GoodFindOne?.name}
             categories={data?.GoodFindOne?.categories}
             price={data?.GoodFindOne?.price}

+ 1 - 1
js21 react/my-react-app/src/pages/admin/UsersPage.js

@@ -1,5 +1,5 @@
 import { Paper, Table, TableBody, TableCell, TableContainer, TableHead, TablePagination, TableRow } from '@mui/material';
-import React, { useEffect, useState } from 'react';
+import React, { useState } from 'react';
 import { useGetUserCountQuery, useGetUsersQuery } from '../../store/api';
 import Loader from '../../components/Loader';
 import { getDateString } from '../../functions/getDataString';

+ 0 - 1
js21 react/my-react-app/src/store/cartSlice.js

@@ -1,5 +1,4 @@
 import { createSlice, current } from "@reduxjs/toolkit";
-import { api } from "./api";
 
 const getItemIndex = (state, idToFind) => {
   const idsArr = state.goods.map(item => item.good._id);