Combine reducers function for context API and hooks

Viewed 365

I'm trying to make a redux like behavior with context API and hooks I have multiple reducers now I'm writing a function to combine them all. It would not be a hard task if I'm not using TypeScript but I want my code to be type-safe I'm struggling with the function below is my attemp and the errors I have.

const combineReducers = <
    S extends AuthType | AppMenuType | LayoutType,
    A extends AppMenuActions | AuthActions | LayoutActions
>(reducers: {
    [key: string]: Reducer<S, A>;
}) => {
    return (state: InitialStateType, action: A) => {
        const keys = Object.keys(reducers);
        const globalState: InitialStateType = { ...state };
        keys.forEach((key) => {
            globalState[key] = reducers[key](globalState[key], action);
        });
        return globalState;
    };
};

so the idea is I want to use the function like this:

const mainReducer = combineReducers({ appMenu: AppMenuReducer, auth: AuthReducer, layout: LayoutReducer });

and then just pass this main Reducer into my useReducer hook like this:

const [state, dispatch] = useReducer(mainReducer, INIT_STATE);

^ the above useage of combineReducers() give me an error like this:

 Types of parameters 'state' and 'prevState' are incompatible.
    Type 'AppMenuType' is missing the following properties from type 'AuthType': user, loading, error, passwordResetStatusts(2322)

from reading the error I think it is complaining about the unions that I'm using on the the combineReducers function. I'm stuck please help! Thank you very much!

0 Answers
Related