Parcourir la source

rtk_startpromises

Gennadysht il y a 2 ans
Parent
commit
83271a95f1

+ 8 - 1
src/App.js

@@ -15,7 +15,14 @@ import './App.css';
 import { CCategory } from './Components/Category';
 
 export const history = createBrowserHistory();
-export const store = createStore(combineReducers({ promise: promiseReducer, auth: authReducer, frontend: frontEndReducer }), applyMiddleware(thunk));
+//export const store = createStore(combineReducers({ promise: promiseReducer, auth: authReducer, frontend: frontEndReducer }), applyMiddleware(thunk));
+export const store = configureStore({
+  reducer: {
+    auth: authReducer,
+    promise: promiseReducer,
+    frontend: frontEndReducer
+  }
+});
 store.subscribe(() => console.log(store.getState()))
 
 //console.log(useParams)

+ 1 - 1
src/Components/RootCats.js

@@ -6,7 +6,7 @@ import { actionCategoryFindOne } from "../reducers";
 export const CatsList = ({ cats = [] }) => {
     return (
         <List>
-            {cats.map(cat => (
+            {cats?.map(cat => (
                 <CatItem cat={cat} key={cat._id} />
             ))}
         </List>

+ 32 - 1
src/reducers/authReducer.js

@@ -1,7 +1,32 @@
 import { jwtDecode } from '../utills';
 import { history } from "../App";
+import { createSlice } from '@reduxjs/toolkit';
 
-export function authReducer(state = {}, action) {                   // диспетчер обработки login
+const authReducerSlice = createSlice({
+    name: "auth",
+    initialState: {},
+    reducers: {
+        login(state, action) {
+            state.payload = jwtDecode(action.token);
+            if (!state.payload) {
+                state.token = undefined;
+            }
+            if (state.token)
+                localStorage.authToken = state.token;
+            else
+                delete localStorage.authToken;
+            history.push('/');
+            return state;
+        },
+        logout(state, action) {
+            state.token = undefined;
+            state.payload = undefined;
+            delete localStorage.authToken;
+            return state;
+        }
+    }
+});
+/*export function authReducer(state = {}, action) {                   // диспетчер обработки login
     if (action) {
         if (action.type === 'AUTH_LOGIN') {
             let newState = { ...state };
@@ -31,3 +56,9 @@ export const actionAuthLogin = token => ({ type: 'AUTH_LOGIN', token });
 export const actionAuthLogout = () => ({ type: 'AUTH_LOGOUT' });
 
 export const actionAuthLoginThunk = token => dispatch => dispatch(actionAuthLogin(token));
+*/
+let authReducer = authReducerSlice.reducer;
+let actionAuthLogin = authReducerSlice.actions.login;
+let actionAuthLogout = authReducerSlice.actions.logout;
+const actionAuthLoginThunk = token => dispatch => dispatch(actionAuthLogin(token));
+export { authReducer, actionAuthLogin, actionAuthLogout, actionAuthLoginThunk };

+ 36 - 1
src/reducers/frontEndReducer.js

@@ -1,3 +1,37 @@
+import { createSlice } from "@reduxjs/toolkit"
+import {store} from "../App";
+
+const frontEndReducerSlice = createSlice({ //promiseReducer
+    name: 'frontend', //префикс типа наподобие AUTH_
+    initialState: { sidebar: {}, ordersPaging: { fromPage: 0, pageSize: 5 } }, //state={} в параметрах
+    reducers: {
+        setSidebar(state, action) {
+            state.sidebar = { opened: action.payload.open };
+            return state;
+        },
+        setOrdersPaging(state, action) {
+            state.ordersPaging = { fromPage: action.page.fromPage, pageSize: action.page.pageSize };
+            return state;
+        },
+        setOrdersSearch(state, action) {
+            state.ordersSearchStr = action.searchStr;
+            return state;
+        }
+    }
+})
+
+let frontEndReducer = frontEndReducerSlice.reducer;
+let actionSetSidebar = open => 
+    async dispatch => {
+        dispatch(frontEndReducerSlice.actions.setSidebar({ open }))
+    }
+
+let actionSetOrdersPaging = frontEndReducerSlice.actions.setOrdersPaging;
+let actionSetOrderSearch = frontEndReducerSlice.actions.setOrdersSearch;
+export { frontEndReducer, actionSetSidebar, actionSetOrdersPaging, actionSetOrderSearch };
+
+
+/*
 export function frontEndReducer(state = { sidebar: {}, ordersPaging: { fromPage: 0, pageSize: 5 } }, action) {                   // диспетчер обработки login
     if (action) {
         if (action.type === 'SET_SIDE_BAR') {
@@ -15,4 +49,5 @@ export function frontEndReducer(state = { sidebar: {}, ordersPaging: { fromPage:
 export const actionSetSidebar = open => ({ type: 'SET_SIDE_BAR', open });
 
 export const actionSetOrdersPaging = (page = { fromPage: 0, pageSize: 5 }) => ({ type: 'SET_ORDERS_PAGING', page });
-export const actionSetOrderSearch = searchStr => ({ type: 'SET_ORDERS_SEARCH', searchStr });
+export const actionSetOrderSearch = searchStr => ({ type: 'SET_ORDERS_SEARCH', searchStr });
+*/

+ 42 - 2
src/reducers/promiseReducer.js

@@ -1,4 +1,44 @@
-export function promiseReducer(state = {}, action) {                   // диспетчер обработки
+import { createSlice } from "@reduxjs/toolkit"
+
+const promiseReducerSlice = createSlice({ //promiseReducer
+    name: 'promise', //префикс типа наподобие AUTH_
+    initialState: {}, //state={} в параметрах
+    reducers: {
+        pending(state, { payload: { name } }) { //if (type === 'promise/pending')
+            state[name] = { status: 'PENDING' }
+        },
+        fulfilled(state, { payload: { name, payload } }) { //if (type === 'promise/fulfilled')
+            state[name] = { status: 'FULFILLED', payload }
+        },
+        rejected(state, { payload: { name, error } }) { //if (type === 'promise/rejected')
+            state[name] = { status: 'REJECTED', error }
+        },
+    }
+})
+
+const actionPromise = (name, promise) =>
+    async dispatch => {
+        try {
+            dispatch(promiseReducerSlice.actions.pending({ name }))
+            let payload = await promise
+            if (payload && payload.data)
+                payload = Object.values(payload.data)[0];
+            dispatch(promiseReducerSlice.actions.fulfilled({ name, payload }))
+            return payload
+        }
+        catch (error) {
+            dispatch(promiseReducerSlice.actions.rejected({ name, error }))
+        }
+    }
+
+
+let promiseReducer = promiseReducerSlice.reducer;
+let actionPending = promiseReducerSlice.actions.pending;
+let actionFulfilled = promiseReducerSlice.actions.fulfilled;
+let actionRejected = promiseReducerSlice.actions.rejected;
+export { promiseReducer, actionPending, actionFulfilled, actionRejected, actionPromise };
+
+/*export function promiseReducer(state = {}, action) {                   // диспетчер обработки
     if (action) {
         if (action.type === 'PROMISE') {
             let newState = { ...state };
@@ -26,4 +66,4 @@ export const actionPromise = (name, promise) => {
             dispatch(actionRejected(name, error)) //в случае ошибки - сигнализируем redux, что промис несложился
         }
     }
-}
+}*/