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

How to fix Property 'incrementCount' does not exist on type 'ContextType | undefined'

$
0
0

I am trying to abstract the logic of useContext and useReducer to not repeat the code whenever i create a new context but i ran in to some problems when i try to strongly type createContext with typescript.

With this function i automate context creation:

import React, { createContext, ReactElement, useReducer } from 'react';type ProviderProps = {    children: ReactElement;};type ActionType = {  type: string;    payload?: any;};export default function <StateType>(    reducer: (state: StateType, action: ActionType) => StateType,    actions: any,    initialState: StateType,) {    type ContextType = {        state: StateType;        actions:{            [k: string]: Function;        }    };    const Context = React.createContext<ContextType | undefined>(undefined);    const Provider = ({ children }: ProviderProps) => {        const [state, dispatch] = useReducer(reducer, initialState);        const boundActions: any = {};        for (let key in actions) {            boundActions[key] = actions[key](dispatch);        }        return (<Context.Provider value={{ state, actions:{                ...boundActions            } }}>                {children}</Context.Provider>        );    };    return { Context, Provider };}

Example context creation:

import createDataContext from './createDataContext';import { INCRASE_COUNT, DECRASE_COUNT } from './ActionTypes';type ActionType = {    type: string;    payload?: any;};type StateType = {    count: number;};const reducer = (state: StateType, action: ActionType) => {    switch (action.type) {        case INCRASE_COUNT:            return { count: state.count + 1 };        case DECRASE_COUNT:            return { count: state.count - 1 };        default:            return state;    }};const incrementCount = (dispatch: React.Dispatch<any>) => {    return () => {        dispatch({ type: INCRASE_COUNT });    };};const decrementCount = (dispatch: React.Dispatch<any>) => {    return () => {        dispatch({ type: DECRASE_COUNT });    };};export const { Context, Provider } = createDataContext<StateType>(    reducer,    {        incrementCount,        decrementCount,    },    { count: 69 },);

When i use it:

import { Context as ExampleContext } from '../context/ExampleContext';const { state, actions } = useContext(    ExampleContext,);

it underlines state and actions with a red line and says:Property 'state, actions' does not exist on type 'ContextType | undefined'

What did i do wrong here is there something that i missed?

PLZZZZZZ HELP ME.


Viewing all articles
Browse latest Browse all 6287

Trending Articles



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