I'm trying to apply generic types for createDataContext helper function in React, I already spent some time, but have had no luck doing it. I'm trying to use a typescript as most as I can, but probably some gaps don't allow me to complete this task on my own, so I'm asking you for help. Thank you
- state could contain any props
- every action could have various params in the second function
- reducer needs to have a specific type from react extended with custom state and actions union type
- the goal is to get defined types of actions and state whenever useContext will be used, the corresponding tip should be shown
const { state, delete } = useContext(MyContext); // in IDE hint "delete: (prop: string) => void"
Incoming data:
const state: SomeCustomStateType = {
prop1: [],
prop2: 123,
prop3: 'hello'
};
// actions
const add = (type: string, payload: any) => () => {},
const delete = (type: string, payload: any) => (prop: string) => {}
const reducer: Reducer<SomeCustomStateType, SomeCustomActionsType> = function (state, actions) {};
Function itself:
export function createDataContext(reducer, actions, initialState) {
const Context = createContext(initialState);
const Provider = ({ children }) => {
const [state, dispatch] = useImmerReducer(reducer, initialState);
// const [state, dispatch] = useReducer(reducer, initialState);
let boundActions = {};
for (let key in actions) {
boundActions[key] = actions[key](dispatch);
}
return <Context.Provider value={{ state, ...boundActions }}>{children}</Context.Provider>;
};
return { Context, Provider };
};
Usage:
export const { Context, Provider } = createDataContext(reducer, { add, delete }, state);