Newer
Older
import { PayloadAction, createSlice } from '@reduxjs/toolkit'
import { CategoryType } from '@shared/types/category.type'
import { ThunkDTO, ThunkPersist } from '@shared/types/thunk.type'
import { RoutineHolderSingleton } from '@utils/routine-holder.singleton'
import { RoutineManager } from '@utils/routine.manager'
import { REHYDRATE } from 'redux-persist'
import { RootState } from '../../stores'
import { startListening } from '../../stores/middleware/listener.middleware'
import { setToken } from './user.reducer'
export interface ReducerState {
thunks: Record<CategoryType, ThunkPersist | null>
const RoutineSlice = createSlice({
name: 'routine',
addRoutine: (state: any, { payload }: PayloadAction<ThunkDTO>) => {
const thunk: ThunkPersist = {
category: payload.category,
payload: payload.payload,
thunkId: payload.thunk.id
}
state.thunks[payload.category] = thunk
state.thunks = initialState.thunks
export const { addRoutine } = RoutineSlice.actions
predicate: (action) => setToken.match(action) && action.payload === null,
listenerApi.dispatch(RoutineSlice.actions.removeAll())
// TODO -> thunk does not have the thunk function object due to its coming from the store that ignores the value.
// at this point we have to figure out how to get the thunk function out of the "string" name
startListening({
predicate: ({ type }) => type === REHYDRATE,
effect: async (_, listenerApi) => {
const { routine } = listenerApi.getState() as RootState
const routines = RoutineHolderSingleton.getInstance()
Object.values(routine.thunks)
.filter(thunk => !!thunk)
.forEach(thunk => {
const container = routines.getRoutineById(thunk.thunkId)
const dto: ThunkDTO = {
category: thunk.category,
payload: thunk.payload,
thunk: container
}
listenerApi.dispatch(addRoutine(dto))
})
},
})
/**
* Add new routine
*
* This listener handles the connection between the RoutingManager that
* stores the non persistable thunk object and the peristable thunk information.
* The persistable information are stored in this reducer
*/
predicate: (action) => addRoutine.match(action),
const { thunk } = action.payload as ThunkDTO
const subscription = await listenerApi.dispatch(thunk.func(action.payload.payload))
RoutineManager.add(subscription.payload, action.payload.category)
// unsubscribe old routine
startListening({
predicate: (action) => addRoutine.match(action),
effect: async (action, listenerApi) => {
const { routine } = listenerApi.getOriginalState() as RootState
const category = action.payload.category;
const lastThunk = routine.thunks[category as CategoryType]
if (lastThunk) {
RoutineManager.unsubscribe(category)