70 lines
2.5 KiB
TypeScript
70 lines
2.5 KiB
TypeScript
import { configureStore, createListenerMiddleware } from '@reduxjs/toolkit';
|
||
import challengeReducer from './challengeSlice';
|
||
import checkinReducer, { addExercise, autoSyncCheckin, removeExercise, replaceExercises, setNote, toggleExerciseCompleted } from './checkinSlice';
|
||
import exerciseLibraryReducer from './exerciseLibrarySlice';
|
||
import foodLibraryReducer from './foodLibrarySlice';
|
||
import goalsReducer from './goalsSlice';
|
||
import healthReducer from './healthSlice';
|
||
import moodReducer from './moodSlice';
|
||
import nutritionReducer from './nutritionSlice';
|
||
import scheduleExerciseReducer from './scheduleExerciseSlice';
|
||
import tasksReducer from './tasksSlice';
|
||
import trainingPlanReducer from './trainingPlanSlice';
|
||
import userReducer from './userSlice';
|
||
import waterReducer from './waterSlice';
|
||
import workoutReducer from './workoutSlice';
|
||
|
||
// 创建监听器中间件来处理自动同步
|
||
const listenerMiddleware = createListenerMiddleware();
|
||
|
||
// 监听所有数据变动的 actions,触发自动同步
|
||
const syncActions = [addExercise, removeExercise, replaceExercises, toggleExerciseCompleted, setNote];
|
||
syncActions.forEach(action => {
|
||
listenerMiddleware.startListening({
|
||
actionCreator: action,
|
||
effect: async (action, listenerApi) => {
|
||
const state = listenerApi.getState() as any;
|
||
const date = action.payload?.date;
|
||
|
||
if (!date) return;
|
||
|
||
// 延迟一下,避免在同一事件循环中重复触发
|
||
await new Promise(resolve => setTimeout(resolve, 100));
|
||
|
||
// 检查是否还有待同步的日期
|
||
const currentState = listenerApi.getState() as any;
|
||
const pendingSyncDates = currentState?.checkin?.pendingSyncDates || [];
|
||
|
||
if (pendingSyncDates.includes(date)) {
|
||
listenerApi.dispatch(autoSyncCheckin({ date }));
|
||
}
|
||
},
|
||
});
|
||
});
|
||
|
||
export const store = configureStore({
|
||
reducer: {
|
||
user: userReducer,
|
||
challenge: challengeReducer,
|
||
checkin: checkinReducer,
|
||
goals: goalsReducer,
|
||
health: healthReducer,
|
||
mood: moodReducer,
|
||
nutrition: nutritionReducer,
|
||
tasks: tasksReducer,
|
||
trainingPlan: trainingPlanReducer,
|
||
scheduleExercise: scheduleExerciseReducer,
|
||
exerciseLibrary: exerciseLibraryReducer,
|
||
foodLibrary: foodLibraryReducer,
|
||
workout: workoutReducer,
|
||
water: waterReducer,
|
||
},
|
||
middleware: (getDefaultMiddleware) =>
|
||
getDefaultMiddleware().prepend(listenerMiddleware.middleware),
|
||
});
|
||
|
||
export type RootState = ReturnType<typeof store.getState>;
|
||
export type AppDispatch = typeof store.dispatch;
|
||
|
||
|