Gennadysht il y a 2 ans
Parent
commit
6db1721db0

+ 4 - 4
src/App.js

@@ -3,8 +3,8 @@ import { combineReducers, configureStore } from '@reduxjs/toolkit';
 import { Router, Route, Switch } from 'react-router-dom';
 import { createBrowserHistory } from "history";
 import { Provider } from 'react-redux';
-import { promiseReducer, frontEndReducer, cartReducer, actionRestoreCart, goodsApi, cartGoodsApi, uploadAPI } from './reducers';
-import { CEditableGood, CGood, CGoodsList, CLoginForm, CMainAppBar, COrder, COrdersList, CSortedFileDropZone } from "./Components";
+import { promiseReducer, frontEndReducer, cartReducer, actionRestoreCart, goodsApi, cartGoodsApi } from './reducers';
+import { CEditableGood, CGood, CGoodsList, CLoginForm, CMainAppBar, COrder, COrdersList, CUser } from "./Components";
 import { CLogout } from './Components';
 import { CSidebar } from './Components/Sidebar';
 import { CRootCats } from './Components';
@@ -42,7 +42,6 @@ const rootReducer = combineReducers({
   [goodsApi.reducerPath]: goodsApi.reducer,
   [ordersApi.reducerPath]: ordersApi.reducer,
   [cartGoodsApi.reducerPath]: cartGoodsApi.reducer,
-  [uploadAPI.reducerPath]: uploadAPI.reducer,
   promise: promiseReducer,
   frontend: frontEndReducer,
   cart: cartReducer,
@@ -55,7 +54,6 @@ export const store = configureStore({
     goodsApi.middleware,
     ordersApi.middleware,
     loginApi.middleware,
-    uploadAPI.middleware,
     cartGoodsApi.middleware],
   reducer: rootReducer
 });
@@ -97,6 +95,8 @@ function App() {
               <Route path="/order/:_id" component={COrder} />
               <Route path="/cart" component={CCart} />
               <Route path="/login" component={CLoginForm} />
+              <Route path="/user" component={CUser} />
+              <Route path="/user/:_id" component={CUser} />
               <Route path="/logout" component={CLogout} />
 
               <Route path="*" component={NotFound} />

+ 24 - 0
src/Components/AboutMe.js

@@ -0,0 +1,24 @@
+import { useSelector } from "react-redux"
+import { useUserFindQuery } from "../reducers";
+import { useParams } from "react-router-dom";
+
+const User = ({ user }) => {
+    return user && (
+        <>
+            <div>
+                {user.nick}
+            </div>
+
+        </>
+    )
+}
+
+const CUser = ({ }) => {
+    const { _id } = useParams();
+    const { isLoading, data } = useUserFindQuery(_id);
+    let user = isLoading ? undefined : data?.UserFindOne;
+    let currentUser = useSelector(state => state.auth.currentUser);
+    user = _id ? user : currentUser;
+    return <User user={user} />
+}
+export { CUser }

+ 2 - 3
src/Components/EditableGood.js

@@ -4,7 +4,7 @@ import { styled } from '@mui/material/styles';
 import { Container, Grid, Card, CardContent, CardMedia, AvatarGroup, CardActions, IconButton, TextField, InputAdornment, Box, Modal } from '@mui/material';
 import { getFullImageUrl } from "./../utills";
 import { useDispatch } from 'react-redux';
-import { useGetGoodByIdQuery, useSaveGoodMutation, useUploadSingleFileMutation } from '../reducers';
+import { useGetGoodByIdQuery, useSaveGoodMutation } from '../reducers';
 import { useParams } from 'react-router-dom';
 import { actionSetCurrentGood } from '../reducers/frontEndReducer';
 import { CSortedFileDropZone } from './SortedFileDropZone';
@@ -161,10 +161,9 @@ const CEditableGood = ({ maxWidth = 'md' }) => {
     const dispatch = useDispatch();
     dispatch(actionSetCurrentGood(_id));
     const [saveGoodMutation, { }] = useSaveGoodMutation();
-    const [uploadSingleFileMutation, { }] = useUploadSingleFileMutation();
 
 
-    return !isLoading && <EditableGood good={good} saveGood={saveGoodMutation} uploadFile={uploadSingleFileMutation} maxWidth={maxWidth} />
+    return !isLoading && <EditableGood good={good} saveGood={saveGoodMutation} maxWidth={maxWidth} />
 }
 
 export { CEditableGood }

+ 1 - 0
src/Components/Good.js

@@ -131,4 +131,5 @@ const CGood = ({ maxWidth = 'md', showAddToCard = true, editable = true }) => {
 
     return <Good good={good} maxWidth={maxWidth} showAddToCard={showAddToCard} editable={editable} actionAddGoodToCart={() => dispatch(actionAddGoodToCart(good))} />
 }
+let a = '';
 export { CGood };

+ 4 - 4
src/Components/LoginForm.js

@@ -3,13 +3,13 @@ import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
 import Button from '@mui/material/Button';
 import { Container, CssBaseline, TextField, Avatar, Typography, FormControlLabel, Checkbox, Grid, Link } from '@mui/material';
 import { Box } from '@mui/system';
-import { connect } from 'react-redux';
+import { connect, useDispatch } from 'react-redux';
 import { MyLink } from './MyLink';
-import { useLoginMutation } from '../reducers/authReducer';
+import { actionAboutMe, useLoginMutation } from '../reducers/authReducer';
 
 const LoginForm = () => {
     const [onLogin, { data, isLoading }] = useLoginMutation()
-    //const dispatch = useDispatch()
+    const dispatch = useDispatch()
 
     const [login, setLogin] = useState('');
     const [password, setPassword] = useState('');
@@ -64,7 +64,7 @@ const LoginForm = () => {
                     fullWidth
                     type="submit"
                     disabled={!isButtonActive}
-                    onClick={() => onLogin({ login, password })}>
+                    onClick={() => onLogin({ login, password }).then(() => dispatch(actionAboutMe()))}>
                     Login...
                 </MyLink>
                 <Grid container>

+ 1 - 0
src/Components/MainAppBar.js

@@ -42,6 +42,7 @@ const MainAppBar = ({ token, openSidebar }) => {
                         <>
                             <MyLink to="/logout"><Button color="inherit">Logout</Button></MyLink>
                             <MyLink to="/orders"><Button color="inherit">Orders</Button></MyLink>
+                            <MyLink to="/user"><Button color="inherit">About Me</Button></MyLink>
                         </>
                     }
                     <MyLink to="/cart"><Button color="inherit">Cart</Button></MyLink>

+ 1 - 0
src/Components/index.js

@@ -12,3 +12,4 @@ export { CMainAppBar } from './MainAppBar';
 export { CRootCats } from './RootCats';
 export { CSortedFileDropZone } from './SortedFileDropZone';
 export { CEditableGood } from './EditableGood'
+export {CUser} from './AboutMe';

+ 21 - 5
src/reducers/authReducer.js

@@ -2,7 +2,7 @@ import { gql } from "graphql-request";
 import { createApi } from '@reduxjs/toolkit/query/react'
 import { graphqlRequestBaseQuery } from '@rtk-query/graphql-request-base-query' //npm install
 import { jwtDecode } from "../utills";
-import { createSlice } from "@reduxjs/toolkit";
+import { createSlice, current } from "@reduxjs/toolkit";
 import { history } from "../App";
 //import { prepareHeaders } from "./index";
 
@@ -71,23 +71,39 @@ const authSlice = createSlice({
             return {}
         }
     },
-    extraReducers: builder =>
+    extraReducers: builder => {
         builder.addMatcher(loginApi.endpoints.login.matchFulfilled,
             (state, { payload }) => {
                 const tokenPayload = jwtDecode(payload.login);
                 if (tokenPayload) {
                     state.token = payload.login;
                     state.payload = tokenPayload;
+                    state.currentUser = { _id: tokenPayload.sub.id };
                     history.push('/');
                 }
-            })
+            });
+        builder.addMatcher(loginApi.endpoints.userFind.matchFulfilled,
+            (state, { payload }) => {
+                let retrievedUser = payload?.UserFindOne;
+                if (retrievedUser?._id === state.currentUser?._id)
+                    state.currentUser = retrievedUser;
+                })
+    }
 })
 
+const actionAboutMe = () =>
+    async (dispatch, getState) => {
+        const auth = getState().auth
+        if (auth.token) {
+            dispatch(loginApi.endpoints.userFind.initiate(auth.currentUser._id))
+        }
+    }
+
 const { logout: actionAuthLogout } = authSlice.actions;
 let authApiReducer = loginApi.reducer;
 let authReducer = authSlice.reducer;
 let authApiReducerPath = loginApi.reducerPath;
 
-export const { useLoginMutation } = loginApi;
-export { authApiReducer, authReducer, authApiReducerPath, actionAuthLogout }
+export const { useLoginMutation, useUserFindQuery } = loginApi;
+export { authApiReducer, authReducer, authApiReducerPath, actionAuthLogout, actionAboutMe }
 

+ 1 - 2
src/reducers/index.js

@@ -1,5 +1,5 @@
 export { promiseReducer, actionPromise, actionFulfilled, actionPending, actionRejected } from "./promiseReducer";
-export { authApiReducer, authReducer, authApiReducerPath, loginApi, authReducerPath, actionAuthLogout } from './authReducer';
+export { authApiReducer, authReducer, authApiReducerPath, loginApi, authReducerPath, useUserFindQuery, actionAuthLogout } from './authReducer';
 export { cartReducer, actionAddGoodToCart, actionDeleteGoodFromCart, actionRestoreCart, actionClearCart, /*getCart,*/ } from "./cartReducer";
 export { cartGoodsApi, useGetCartGoodsQuery } from "./cartGoodsReducer";
 export { localStoredReducer, } from "./localStoredReducer";
@@ -7,6 +7,5 @@ export { frontEndReducer, getCurrentCategory, actionSetGoodsPaging, actionSetOrd
 export { useGetRootCategoriesQuery, useGetCategoryByIdQuery } from './categoryReducer';
 export { ordersApi, useGetOrderByIdQuery, useGetOrdersCountQuery, useGetOrdersQuery, useAddOrderMutation } from './ordersReducer';
 export { goodsApi, useGetGoodByIdQuery, useGetGoodsCountQuery, useGetGoodsQuery, useSaveGoodMutation } from './goodsReducer';
-export { uploadAPI, useUploadSingleFileMutation } from './uploadReducer';
 
 

+ 0 - 55
src/reducers/uploadReducer.js

@@ -1,55 +0,0 @@
-import { resolveComponentProps } from '@mui/base';
-import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
-import { graphqlRequestBaseQuery } from "@rtk-query/graphql-request-base-query";
-var FormData = require('form-data');
-
-const prepareHeaders = (headers, { getState }) => {
-  const token = getState().auth.token;
-  if (token) {
-    headers.set("Authorization", `Bearer ${token}`);
-    headers.set("Content-Type", "multipart/form-data");
-  }
-  return headers;
-}
-
-const uploadAPI = createApi({
-  reducerPath: 'uploadAPI',
-  baseQuery: fetchBaseQuery(
-    {
-      baseUrl: "http://shop-roles.node.ed.asmer.org.ua/",
-      prepareHeaders
-    }),
-  endpoints: (builder) => ({
-    uploadSingleFile: builder.mutation({
-      async query(file) {
-        var formData = new FormData();
-        let fileData = await file.data.arrayBuffer();
-        formData.append('photo', fileData);
-        /*var reader = new FileReader();
-        const readFile = (event) => event.target.result; 
-        reader.addEventListener("loadend", readFile);
-        reader.readAsBinaryString(file.data);
-            <input type="file" name="photo" id='photo' value={file.url} />
-        let form = (
-          <form action="/upload" method="post" enctype="multipart/form-data" id='form'>
-            <input type="number" name="photo1" id='photo1' value={5} />
-          </form>
-        );
-        */
-
-        let res =
-        {
-          action:"/upload",
-          //url: 'upload',
-          method: 'POST',
-          credentials: 'include',
-          body: formData,
-        };
-        return res;
-      },
-    }),
-  }),
-});
-
-export const { useUploadSingleFileMutation } = uploadAPI;
-export { uploadAPI }

+ 0 - 2
src/utills/utils.js

@@ -1,5 +1,3 @@
-import { useSelector } from "react-redux";
-
 const getFullImageUrl = (image) =>
         `/${image?.url}`;