Skip to content

Instantly share code, notes, and snippets.

@arnotes
Created May 25, 2020 00:44
Show Gist options
  • Save arnotes/337735967d46df1848eda57dfdb4e578 to your computer and use it in GitHub Desktop.
Save arnotes/337735967d46df1848eda57dfdb4e578 to your computer and use it in GitHub Desktop.
becase createSlice doesnt support a 'default case'
import { Slice } from "@reduxjs/toolkit";
import { studentSlice } from "./studentSlice";
type childSelector<P,C> = (state:P) => C;
export const forwardReducer = <P,C>(childSlice:Slice<C>,childSelector:childSelector<P,C>) => {
const reducerDC = {} as any;//will fix types later
for (const key in childSlice.actions) {
if (childSlice.actions.hasOwnProperty(key)) {
const action = childSlice.actions[key];
reducerDC[action.type] = (state:P, action:any) => {
childSlice.reducer(childSelector(state), action);
}
}
}
console.log({reducerDC, childSlice});
return reducerDC;
}
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { student } from "./student.interface";
export const studentSlice = createSlice({
name: 'student',
initialState: {} as any as student,
reducers:{
setGrade:(state, action:PayloadAction<string>) => {
state.studentGrade = action.payload
}
}
})
import { createSlice } from "@reduxjs/toolkit";
import { teacher } from "./teacher.interface";
import { forwardReducer } from "./forwardReducer";
import { studentSlice } from "./studentSlice";
import { student } from "./student.interface";
export const teacherSlice = createSlice({
name: 'teacher',
initialState: {student:{}} as any as teacher,
reducers:{
setName:(state, action) => {
state.teacherName = action.payload
}
},
extraReducers: forwardReducer<teacher, student>(studentSlice, state => state.student)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment