Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Trying to apply correct types for createDataContext function in React using typescript generics

$
0
0

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

  1. state could contain any props
  2. every action could have various params in the second function
  3. reducer needs to have a specific type from react extended with custom state and actions union type
  4. 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'};// actionsconst 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);

Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>