Home > Software design >  React custom hook with useContext functions
React custom hook with useContext functions

Time:05-21

when i try to use a function inside a custom hook the following error happens:

Uncaught TypeError: tglCartao is not a function

my custom hook at UseCartao.tsx:

export interface ICartaoContext {
    idToggleKey     : string;
    setIdToggleKey? : any;

    arrayCartoes    : Array<any>;
    setArrayCartoes?: any;

    tglCartao?:(numeroCartao: string) => void;
};

const defaultValue = {
    idToggleKey     : '1',
    arrayCartoes    : [
        {
            NR_CARTAO: 1,
            INVALIDO: false,
            SELECIONADOS: [] 
        },
    ]
};

const CartaoContext = createContext<ICartaoContext>(defaultValue);

export const CartaoProvider: FC<any> = ({ children } : any) => {
    const Cartao = UseCartaoProvider();
    return <CartaoContext.Provider value={{...Cartao}}>{children}</CartaoContext.Provider>;
};

export const useCartao = () => {
    return useContext(CartaoContext);
};

const UseCartaoProvider = () => {
    const [idToggleKey, setIdToggleKey] = useState<string>('1');
    const [arrayCartoes, setArrayCartoes] = useState<Array<any>>(
        [
            {
                NR_CARTAO: 1,
                INVALIDO: false,
                SELECIONADOS: [] 
            },
        ]
    ); 

    const tglCartao = useCallback((numeroCartao: string) : void => {
        setIdToggleKey(numeroCartao);
    }, [setIdToggleKey]);

    return ({
        idToggleKey,
        arrayCartoes,
        tglCartao: tglCartao,
    })
}

export default useCartao;

my button in the index.tsx calling the function tglCartao:

onClick={() => tglCartao!(idToggleKey === item.NR_CARTAO ? '0' : item.NR_CARTAO)}

and yes, all my index.tsx return code is inside <CartaoProvider> </CartaoProvider>

CodePudding user response:

Maybe CartaoProvider and your button is using in same level, make sure you dont call it like below

EX

const tglCartao = useHookFromContext() //your context from CartaoProvider

<CartaoProvider> 

</CartaoProvider>

Because in that you even call context before wrap it in Provider

Correct way EX

<CartaoProvider> 
    <Child/>
</CartaoProvider>


const Child = () => {
     const tglCartao = useHookFromContext() //your context from CartaoProvider
     ....
}
  • Related